根據上一篇的設計,貓哥想實現的是對于類似的某種實體概念(比如人員)的增刪改查操作,將相似的邏輯封裝一下,不用每次都寫重復的部分。扯得遠了點,直接看具體如何實現的:
在具體實現之前,先展示下效果,需要注意,貓哥將表格美工,內容部分美工,整個后臺頁面美工的CSS文件都單獨抽取出來了,因為css不是本系列的重點且此前已經詳細講過了,此處不再貼代碼。
a,登錄成功后 b,點擊人員管理后
c,點擊人員編碼7右邊對應的刪除后
d,點擊人員編碼2右邊對應的編輯后
e,點擊保存后
1,首先就是菜單信息的參數化,因為增、刪、改、查等功能都是規定好的以/HomeworkSystem/AcitonServlet?method=XXX&entity=YYY&id=ZZZ
中的參數為區分,所以將Constant類修改為:
2,從登錄頁面到LoginServlet,登錄錄成功后跳轉index.jsp,此時index.jsp中的菜單加載部分需要修改如一下,主要有兩處,一是菜單欄每一個菜單href屬性指向參數化了,二是右側內容區對應網址修改為actionUrl,貓哥感覺actionUrl更能表達此刻的心意,哈哈。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@ taglib 3,好的,來到CRUD操作控制的核心ActionServlet了,此時都是使用if判斷的,針對不同的網頁請求,采用不同的處理操作:package servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import command.ActionCommand;import entity.*;import java.util.List;public class ActionServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response);//doGet與doPost一樣處理 } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //輸入輸出設置 response.setContentType("text/html"); request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); //獲取標準Action動作的三個參數 String method=request.getParameter("method"); String entityType=request.getParameter("entity"); String id=request.getParameter("id"); //處理 String actionUrl=doAction(request,method,entityType,id); request.setAttribute("actionUrl",actionUrl); //跳轉 request.getRequestDispatcher("/index.jsp").forward(request,response); } //具體細分的控制處理,返回內容區域應該顯示的網頁地址 private String doAction(HttpServletRequest request,String method,String entityType,String entityId){ String url="";//初始化返回值 ActionCommand actionCommand=new ActionCommand(entityType);//處理數據庫邏輯 if(method.equals("view")){//查看 List entityList=actionCommand.selectAll(); request.setAttribute("entityList",entityList); url=entityType.toLowerCase()+"Manage.jsp"; }else if(method.equals("delete")){//刪除 actionCommand.deleteById(entityId); List entityList=actionCommand.selectAll(); request.setAttribute("entityList",entityList);//更新名單 url=entityType.toLowerCase()+"Manage.jsp"; }else if(method.equals("edit")){//修改 Object entity=actionCommand.selectById(entityId); request.setAttribute("editEntity", entity); url=entityType.toLowerCase()+"Update.jsp"; }else if(method.equals("add")){//新增 url=entityType.toLowerCase()+"Update.jsp"; }else if(method.equals("save")){//保存 //因保存時各類實體代碼各不一致,導致寫在此處會很難看,所以由單獨提取成一個方法 this.doSaveAction(request,entityType,actionCommand); List entityList=actionCommand.selectAll(); request.setAttribute("entityList",entityList);//更新名單 url=entityType.toLowerCase()+"Manage.jsp"; } return url; } //單獨處理save,因為save方法是跟具體的實體類結構相關 private void doSaveAction(HttpServletRequest request,String entityType,ActionCommand actionCommand){ String id=request.getParameter("hiddenId"); Object entity=null; //------------------------------------------------------------------------------- //此處為組裝區域,根據不同頁面內容是變化的,其余部分都是按一定規則固定了的 if(entityType.equals("User")){ User user=new User(); if(!"".equals(id))//修改 user.setUserId(Integer.parseInt(id)); else//新增 user.setUserPassWord("1234");//初始化密碼 user.setUserName(request.getParameter("userName")); Role role=new Role(); role.setRoleId(Integer.parseInt(request.getParameter("userRole"))); user.setUserRole(role); entity=user; } //------------------------------------------------------------------------------- //實體修改到數據庫 if(!"".equals(id)){//修改 actionCommand.update(entity); }else{//添加 actionCommand.add(entity); } }}4,其中數據庫操作部分是調用ActionCommand實現的,ActionCommand具體如下:
package command;import java.util.List;import javax.servlet.http.HttpServletRequest;import entity.*;import Operation.*;public class ActionCommand{ private String entityType; public ActionCommand(String type){ entityType=type; } public List selectAll(){ ObjectOperation oper=OperationFactory.createOperation(entityType); return oper.selectAll(); } public int deleteById(String id){ ObjectOperation oper=OperationFactory.createOperation(entityType); return oper.deleteById(id); } public Object selectById(String id){ ObjectOperation oper=OperationFactory.createOperation(entityType); return oper.selectById(id); } public int add(Object entity){ ObjectOperation oper=OperationFactory.createOperation(entityType); return oper.add(entity); } public int update(Object entity){ ObjectOperation oper=OperationFactory.createOperation(entityType); return oper.update(entity); }}發現ActionCommand的代碼倒是非常精簡啊,因為本來就是要增刪改查嘛。好的,至于數據庫操作層的代碼,此處就不細講了,需要的可自行翻看以前的章節。
5,下面先來實現人員管理的列表頁面userManage.jsp如下:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!-- 使用c:標簽需要添加本行代碼 --><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>userManage.jsp</title> <link href="css/content.css" type="text/css" rel="stylesheet"/> <link href="css/table.css" type="text/css" rel="stylesheet"/> </head> <body> <div id="user_top"> 人員管理 </div><!-- user_top end --> <div id="user_mid"> <table class="table_theme1"> <thead> <th>人員編碼</th> <th>姓名</th> <th>角色</th> <th>操作</th> <th>操作</th> </thead> <c:forEach items="${entityList}" var="item"> <tr> <td>${item.userId}</td> <td>${item.userName}</td> <td>${item.userRole.roleName}</td> <td><a href="/HomeworkSystem/ActionServlet?method=edit&entity=User&id=${item.userId}">編輯</a></td> <td><a href="/HomeworkSystem/ActionServlet?method=delete&entity=User&id=${item.userId}">刪除</a></td> </tr> </c:forEach> </table> </div><!-- user_mid end --> <div id="user_bottom"> <a href="/HomeworkSystem/ActionServlet?method=add&entity=User">新增</a> </div><!-- "user_bottom" end --> </body></html>6,最后,實現人員管理修改/新增時的頁面:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!-- 使用c:標簽需要添加本行代碼 --><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>userUpdate.jsp</title> <link href="css/content.css" type="text/css" rel="stylesheet"/> <link href="css/table.css" type="text/css" rel="stylesheet"/> </head> <body> <form action="/HomeworkSystem/ActionServlet?method=save&entity=User" method="post"> <div id="user_top"> 人員信息更新 </div><!-- user_top end --> <div id="user_mid"> <table class="table_theme1"> <tr> <td>姓名:</td> <td> <input type="text" name="userName" value="${editEntity.userName}"/> <input type="hidden" name="hiddenId" value="${editEntity.userId}"/> </td> </tr> <tr> <td>角色:</td> <td> <select name="userRole"><!-- 編輯情況下,默認顯示編輯用戶的角色的功能,待后續優化項目時再講如何實現 --> <option value="1">校長</option> <option value="2">老師</option> <option value="3">學生</option> </select> </td> </tr> </table> </div><!-- user_mid end --> <div id="user_bottom"> <input type="submit" value="保存"></input> </div><!-- "user_bottom" end --> </form> </body></html>最后總結一下子,因為有了通用的CRUD后端,我們每次添加一個實體(比如課程、人員、角色等等)的增刪改查功能時,只需要建立兩個網頁xxxManage.jsp和xxxUpdate.jsp,并按照規則修改里面的鏈接和具體信息(每種實體內容不同),然后在ActionServlet的 doSaveAction方法里添加新的if分支以保存新類型的實體就行了。
怎么感覺一下子就簡單了呢,這樣的一個通用CRUD后端設計合理嗎,能實現所有功能嗎,易拓展嗎?這個問題留待下篇分解。
新聞熱點
疑難解答