1. MVC 设计模式 1.1 MVC 模式 MVC 设计模式核心概念: ● Model 模型层,数据封装 ● View 视图层,数据可视 ● Controller 控制层,请求处理 + 业务处理 + 数据库操作 缺点:控制层代码太多,违背单一职责原则,因此引入三层架构设计。
Model + View + 三层架构(Controller + Service + Dao)
● Controller 控制层,只处理请求 ● Service 业务层,只处理业务 ● Dao 持久层,只处理数据库操作
1.2 Spring 分层体系结构
2. 案例:用户管理实现 主界面 :
核心功能 : JSP + MVC + 三层架构设计实现,用户信息(id/username/password)的注册、删除、修改、查询展示所有、登陆、登出。
核心流程图 (点击/拖动均可放大): User.java
1 2 3 4 5 6 public class User { private Integer id; private String username; private String password; ... }
BaseServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 @WebServlet(name = "BaseServlet", urlPatterns = "/base") public class BaseServlet extends HttpServlet { @Override protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String methodName = request.getParameter("methodName" ); System.out.println("BaseServlet methodName=" + methodName); try { Method method = this .getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class); String returnValue = (String) Objects.requireNonNull(method).invoke(this , request, response); if (null != returnValue) { int index = returnValue.lastIndexOf(":" ); if (-1 == index) { request.getRequestDispatcher(returnValue).forward(request, response); } else { String path = returnValue.substring(index + 1 ); if (returnValue.startsWith("redirect" )) { response.sendRedirect(request.getContextPath() + path); } else if (returnValue.startsWith("forward" )) { request.getRequestDispatcher(path).forward(request, response); } } } else { } } catch (Exception e) { e.printStackTrace(); } } @Override protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
2.1 注册 register.jsp
1 2 3 4 5 6 7 <div style ="color: red;" > ${errorMsg}</div > <form action ="${pageContext.request.contextPath}/user" method ="post" > <input type ="hidden" name ="methodName" value ="registerUser" > 账户:<input type ="text" name ="username" placeholder ="请输入用户名" > <br > 密码:<input type ="text" name ="password" placeholder ="请输入密码" > <br > <button type ="submit" > 注册</button > </form >
index.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 <table border ="1" cellspacing ="0px" cellpadding ="5px" width ="500px" > <tr > <td > ID</td > <td > 账户</td > <td > 密码</td > <td > 操作</td > </tr > <c:forEach items ="${userList}" var ="user" > <tr > <td > ${user.id}</td > <td > ${user.username}</td > <td > ${user.password}</td > <td > <a href ="${pageContext.request.contextPath}/user?methodName=toUpdateUserById&id=${user.id}" > 修改</a > <c:if test ="${existUser.username != user.username}" > <a href ="${pageContext.request.contextPath}/user?methodName=deleteUserById&id=${user.id}" > 删除</a > </c:if > </td > </tr > </c:forEach > </table >
UserServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public String registerUser (HttpServletRequest request, HttpServletResponse response) { User inputUser = new User (); try { BeanUtils.populate(inputUser, request.getParameterMap()); userService.registerUser(inputUser); return "/user?methodName=selectUserList" ; } catch (Exception e) { e.printStackTrace(); } request.setAttribute("errorMsg" , "注册失败!" ); return "/user?methodName=registerUser" + "&username=" + inputUser.getUsername() + "&password=" + inputUser.getPassword(); }
UserServiceImpl.java
1 2 3 public boolean registerUser (User inputUser) { return userDao.registerUser(inputUser) == 1 ; }
UserDaoImpl.java
1 2 3 4 5 6 7 8 9 10 11 12 public int registerUser (User inputUser) { try { return queryRunner.update( "insert into user(username, password) value(?,?)" , inputUser.getUsername(), inputUser.getPassword() ); } catch (SQLException e) { e.printStackTrace(); } return -1 ; }
2.2 登陆 login.jsp
1 2 3 4 5 6 7 <div style ="color: red;" > ${errorMsg}</div > <form action ="${pageContext.request.contextPath}/user" method ="post" > <input type ="hidden" name ="methodName" value ="login" > 账户:<input type ="text" name ="username" > <br > 密码:<input type ="text" name ="password" > <br > <button type ="submit" > 登陆</button > </form >
index.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 <%--在登陆状态:显示用户名,提供注销--%><c:if test ="${existUser != null}" > 欢迎回来,<span style ="color: red;" > ${existUser.username}</span > ! <br > <a href ="${pageContext.request.contextPath}/register.jsp" > <button > 新增用户</button > </a > ...</c:if > <%--不在登陆状态:提示登陆--%><c:if test ="${existUser == null}" > 您还没有登陆,<a href ="${pageContext.request.contextPath}/login.jsp" > 请登录</a > </c:if >
UserServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public String login (HttpServletRequest request, HttpServletResponse response) { User inputUser = new User (); try { BeanUtils.populate(inputUser, request.getParameterMap()); User existUser = userService.login(inputUser); if (null != existUser) { request.getSession().setAttribute("existUser" , existUser); return "redirect:/user?methodName=selectUserList" ; } else { request.setAttribute("errorMsg" , "账户或密码错误" ); return "/login.jsp" ; } } catch (Exception e) { e.printStackTrace(); } return "/login.jsp" ; }
UserServiceImpl.java
1 2 3 public User login (User inputUser) { return userDao.login(inputUser); }
UserDaoImpl.java
1 2 3 4 5 6 7 8 9 10 11 12 13 public User login (User inputUser) { try { return queryRunner.query( "select * from user where username=? and password=?" , new BeanHandler <>(User.class), inputUser.getUsername(), inputUser.getPassword() ); } catch (SQLException e) { e.printStackTrace(); } return null ; }
2.3 登陆校验 LoginFilter.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 @Override public void doFilter (ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; String requestURI = request.getRequestURI(); String methodName = request.getParameter("methodName" ); if (requestURI.contains("login" ) || (methodName != null && methodName.equals("login" ))) { chain.doFilter(req, resp); } else { User existUser = (User) request.getSession().getAttribute("existUser" ); if (null == existUser) { response.sendRedirect("/demo/login.jsp" ); } else { chain.doFilter(req, resp); } } }
2.4 注销 index.jsp
1 2 3 ...<a href ="${pageContext.request.contextPath}/user?methodName=logout" > 注销</a > ...
UserServlet.java
1 2 3 4 5 6 7 8 9 10 11 public String logout (HttpServletRequest request, HttpServletResponse response) { try { request.getSession().invalidate(); return "redirect:/index.jsp" ; } catch (Exception e) { e.printStackTrace(); return "/index.jsp" ; } }
2.5 修改 index.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 <table border ="1" cellspacing ="0px" cellpadding ="5px" width ="500px" > ... <c:forEach items ="${userList}" var ="user" > <tr > <td > ${user.id}</td > <td > ${user.username}</td > <td > ${user.password}</td > <td > <a href ="${pageContext.request.contextPath}/user?methodName=toUpdateUserById&id=${user.id}" > 修改</a > </td > </tr > </c:forEach > </table >
UserServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public String toUpdateUserById (HttpServletRequest request, HttpServletResponse response) { Integer id = Integer.valueOf(request.getParameter("id" )); User user = userService.selectUserById(id); request.setAttribute("user" , user); return "/updateUser.jsp" ; }public String updateUser (HttpServletRequest request, HttpServletResponse response) { User inputUser = new User (); try { BeanUtils.populate(inputUser, request.getParameterMap()); userService.updateUserById(inputUser); return "/user?methodName=selectUserList" ; } catch (Exception e) { e.printStackTrace(); } request.setAttribute("errorMsg" , "修改失败!" ); return "/user?methodName=toUpdateUserById&id=" + inputUser.getId(); }
UserServiceImpl.java
1 2 3 4 5 6 7 public User selectUserById (Integer id) { return userDao.selectUserById(id); }public boolean updateUserById (User inputUser) { return userDao.updateUserById(inputUser) == 1 ; }
UserDaoImpl.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 public User selectUserById (Integer id) { try { return queryRunner.query( "select * from user where id=?" , new BeanHandler <>(User.class), id); } catch (SQLException e) { e.printStackTrace(); } return null ; }public int updateUserById (User inputUser) { try { return queryRunner.update( "update user set username=?,password=? where id=?" , inputUser.getUsername(), inputUser.getPassword(), inputUser.getId() ); } catch (SQLException e) { e.printStackTrace(); } return -1 ; }
2.6 删除 index.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 <table border ="1" cellspacing ="0px" cellpadding ="5px" width ="500px" > ... <c:forEach items ="${userList}" var ="user" > <tr > ... <td > <c:if test ="${existUser.username != user.username}" > <a href ="${pageContext.request.contextPath}/user?methodName=deleteUserById&id=${user.id}" > 删除</a > </c:if > </td > </tr > </c:forEach > </table >
UserServlet.java
1 2 3 4 5 public String deleteUserById (HttpServletRequest request, HttpServletResponse response) { Integer id = Integer.valueOf(request.getParameter("id" )); boolean result = userService.deleteUserById(id); return "redirect:/user?methodName=selectUserList" ; }
UserServiceImpl.java
1 2 3 public boolean deleteUserById (Integer id) { return userDao.deleteUserById(id) == 1 ; }
UserDaoImpl.java
1 2 3 4 5 6 7 8 9 10 public int deleteUserById (Integer id) { try { return queryRunner.update( "delete from user where id=?" , id); } catch (SQLException e) { e.printStackTrace(); } return -1 ; }
2.7 批量删除 index.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 <form action ="${pageContext.request.contextPath}/user?methodName=deleteUsersByIds" method ="post" > <table border ="1" cellspacing ="0px" cellpadding ="5px" width ="500px" > ... <c:forEach items ="${userList}" var ="user" > <tr > <td > <input type ="checkbox" name ="ids" value ="${user.id}" > </td > <td > ${user.id}</td > <td > ${user.username}</td > <td > ${user.password}</td > ... </tr > </c:forEach > </table > <br > <button type ="submit" > 批量删除</button > </form >
UserServlet.java
1 2 3 4 5 6 7 8 9 public String deleteUsersByIds (HttpServletRequest request, HttpServletResponse response) { String[] ids = request.getParameterValues("ids" ); if (null != ids) { List<Integer> idList = new ArrayList <>(); Arrays.stream(ids).forEach(id -> idList.add(Integer.valueOf(id))); userService.deleteUsersByIds(idList); } return "/user?methodName=selectUserList" ; }
UserServiceImpl.java
1 2 3 public boolean deleteUsersByIds (List<Integer> idList) { return userDao.deleteUsersByIds(idList) == idList.size(); }
UserDaoImpl.java
1 2 3 4 5 6 7 8 9 10 11 public int deleteUsersByIds (List<Integer> idList) { int numLines = 0 ; for (Integer id : idList) { try { numLines += queryRunner.update("delete from user where id=?" , id); } catch (SQLException e) { e.printStackTrace(); } } return numLines; }