黑马程序员技术交流社区
标题:
【成都校区JavaEE24期】
[打印本页]
作者:
yshshe1700
时间:
2019-5-24 10:13
标题:
【成都校区JavaEE24期】
import cn.itcast.travel.Service.Impl.UserServiceImpl;
import cn.itcast.travel.Service.UserService;
import cn.itcast.travel.domain.ResultInfo;
import cn.itcast.travel.domain.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet("/registUserServlet")
public class RegistUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取验证码
String check = request.getParameter("check");
//通过Session域获取随机产生的验证码
HttpSession session = request.getSession();
String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");
session.removeAttribute("CHECKCODE_SERVER");
//判断验证码是否正确
if (checkcode_server == null || !checkcode_server.equalsIgnoreCase(check)) {
ResultInfo info = new ResultInfo();
info.setFlag(false);
info.setErrorMsg("您输入的验证码错误");
//把info对象转换成Json返回给前端
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);
response.setContentType("application;charset= utf-8");
response.getWriter().write(json);
return;
}
//获取数据
Map<String, String[]> map = request.getParameterMap();
//封装User
User user = new User();
try {
BeanUtils.populate(user,map);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//调用Service完成注册
UserService service = new UserServiceImpl();
boolean flag = service.regist(user);
ResultInfo info = new ResultInfo();
//响应结果
if(flag){
//注册成功
info.setFlag(true);
}else {
//注册失败
info.setFlag(false);
info.setErrorMsg("注册失败!");
}
//将info序列化为json
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(info);
//将json数据写回客户端
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(json);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2