BaseServlet抽取
优化Servlet
减少Servlet的数量,现在是一个功能一个Servlet,将其优化为一个模块一个Servlet,
相当于在数据库中一张表对应一个Servlet,在Servlet中提供不同的方法,完成用户的请求。
UserServlet类:
@WebServlet("/user/*") public class UserServlet extends BaseServlet { public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("userServlet的add方法"); } public void find(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("userServlet的find方法"); } }
BaseServlet类:
public class BaseServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //System.out.println("BaseServlet的service方法被执行"); //完成方法分发 //1、获取请求路径 String uri = req.getRequestURI(); System.out.println("请求的uri:"+uri); //2、获取方法名称 String methodName = uri.substring(uri.lastIndexOf("/") + 1); System.out.println("方法名称:"+methodName); //3、获取方法对象 try { Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); //4、执行方法 method.invoke(this,req,resp); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
UserServlet和页面路径改写
UserServlet类:
@WebServlet("/user/*") public class UserServlet extends BaseServlet { //声明Userservice业务对象 private UserService service = new UserServiceImpl(); /** * 注册功能 * @param request * @param response * @throws ServletException * @throws IOException */ public void regist(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/json;charset=utf-8"); response.getWriter().write(json); return; } //1、获取数据 Map<String, String[]> map = request.getParameterMap(); //2、封装对象 User user = new User(); try { BeanUtils.populate(user,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } //3、调用service完成注册 //UserService service = new UserServiceImpl(); boolean flag = service.regist(user); //4、响应结果 ResultInfo info = new ResultInfo(); if (flag){ //注册成功 info.setFlag(true); }else { //注册失败 info.setFlag(false); info.setErrorMsg("注册失败"); } //将info对象序列化为json ObjectMapper mapper = new ObjectMapper(); String string = mapper.writeValueAsString(info); //将json数据写回客户端 //设置content-type response.setContentType("application/json;charset=utf-8"); response.getWriter().write(string); } /** * 登录功能 * @param request * @param response * @throws ServletException * @throws IOException */ public void login(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/json;charset=utf-8"); response.getWriter().write(json); return; } //1、获取用户名和密码数据 Map<String, String[]> map = request.getParameterMap(); //2、封装User对象 User user = new User(); try { BeanUtils.populate(user,map); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } //3、调用Service查询 //UserService service = new UserServiceImpl(); User u = service.login(user); session.setAttribute("user",u); ResultInfo info = new ResultInfo(); //4、判断用户对象是否存在 if(u==null){ //用户名密码错误 info.setFlag(false); info.setErrorMsg("用户名或密码错误"); } //5、判断用户是否激活 if(u != null && !"Y".equals(u.getStatus())){ //用户尚未激活 info.setFlag(false); info.setErrorMsg("您尚未激活,请激活"); } //6、判断登录成功 if (u!=null && "Y".equals(u.getStatus())){ info.setFlag(true); } //响应数据 ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json;charset=utf-8"); mapper.writeValue(response.getOutputStream(),info); } /** * 查找一个 * @param request * @param response * @throws ServletException * @throws IOException */ public void findOne(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //从session中获取登录用户 Object user = request.getSession().getAttribute("user"); //将user写回客户端 ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json;charset=utf-8"); mapper.writeValue(response.getOutputStream(),user); } /** * 退出 * @param request * @param response * @throws ServletException * @throws IOException */ public void exit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1、销毁session request.getSession().invalidate(); //2、跳转登录页面 response.sendRedirect(request.getContextPath()+"/login.html"); } /** * 激活功能 * @param request * @param response * @throws ServletException * @throws IOException */ public void active(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1、获取激活码 String code = request.getParameter("code"); if (code!=null){ //2、调用service完成激活 //UserService service = new UserServiceImpl(); boolean flag = service.active(code); //3、判断标记 String msg = null; if (flag){ msg = "激活成功,请<a href='/travel/login.html'>登录</a>"; }else { msg = "激活失败,请联系管理员"; } response.setContentType("text/html;charset=utf-8"); response.getWriter().write(msg); } } }
修改页面路径:
regist.html页面:
$(function () { $("#registerForm").submit(function () { //发送数据到服务器 if (checkUsername() && checkPassword() && checkEmail()){ //校验通过发送ajax请求,提交表单的数据 $.post("user/regist",$(this).serialize(),function (data) { //处理服务器响应的数据 if(data.flag){ //注册成功,跳转成功页面 location.href = "register_ok.html"; }else { $("#errorMsg").html(data.errorMsg); } }); } return false; });
header.html页面:
<script> $(function () { $.get("user/findOne",{},function (data) { var msg = "欢迎回来,"+data.name; $("#span_username").html(msg); }); }); </script>
login.html页面:
<script> //1、给登录按钮绑定单击事件 $(function () { $("#btn_sub").click(function () { //2、发送ajax请求,提交表单数据 $.post("user/login",$("#loginForm").serialize(),function (data) { //3、处理响应数据 if (data.flag){ //登录成功 location.href="index.html"; }else { //登录失败 $("#errorMsg").html(data.errorMsg); } }); }); }); </script>
UserServiceImpl实现类:
/** * 注册用户 * @param user * @return */ @Override public boolean regist(User user) { //根据用户名查询用户对象 User u = userDao.findByUsername(user.getUsername()); //判断u是否为null if (u!=null){ //用户名已存在,注册失败 return false; } //保存用户信息 //设置激活码。唯一字符串 user.setCode(UuidUtil.getUuid()); //设置激活状态 user.setStatus("N"); userDao.save(user); //激活邮件发送 String content = "<a href='http://localhost/travel/user/active?code="+user.getCode()+"'>点击激活【旅游网】</a>"; MailUtils.sendMail(user.getEmail(),content,"激活邮件"); return true; }
标签:info,BaseServlet,UserServlet,request,throws,user,new,response,页面 From: https://www.cnblogs.com/xjw12345/p/16620171.html