本文是基於單體架構實現的角色的增刪改查的功能。前臺使用Bootstrap+Ajax+Jsp , 後端使用Spring+SpringMvc+MyBatis進行開發,相信使用過這些技術的小夥伴應該很好的理解如下的內容,也但願看了這篇文章小夥伴們有所收穫。javascript
技術 | 說明 | 官網 |
---|---|---|
Spring | Spring是一個輕量級控制反轉(IoC)和麪向切面(AOP)的容器框架。 | https://spring.io/ |
SpringMvc | MVC框架 | https://spring.io/projects/sp... |
MyBatis | 持久層框架 | https://mybatis.org/mybatis-3... |
Druid | 數據庫鏈接池 | https://github.com/alibaba/druid |
log4j | 日誌框架 | https://logging.apache.org/lo... |
Bootstrap | 簡潔、直觀、強悍的前端開發框架 | https://www.bootcss.com/ |
Ajax | 先後端交互 | https://www.w3school.com.cn/a... |
Jsp | 模板引擎 | https://www.runoob.com/jsp/js... |
layer.js | 消息提示 | http://www.h-ui.net/lib/layer... |
Modal插件 | 模態框(Modal)是覆蓋在父窗體上的子窗體 | https://www.runoob.com/bootst... |
jquery.pagination.js | 分頁插件 | http://www.jq22.com/yanshi5697/ |
在頁面 role-page.jsp引入role.js文件css
<script type="text/javascript" src="script/my-role.js"></script>
分頁實現初始化全局函數,每頁的條數,頁碼,模糊查詢的關鍵詞html
//初始化全局變量 function initGlobalVariable() { window.pageSize = 5; //每頁的條數 window.pageNum = 1; //頁碼 window.keyword = ""; //關鍵詞 }
//給服務器發送請求獲取分頁數據(pageInfo),並在頁面上顯示分頁效果(主體、頁碼導航條) function showPage() { // 給服務器發送請求獲取分頁數據:PageInfo var pageInfo = getPageInfo(); // 在頁面上的表格中tbody標籤內顯示分頁的主體數據 generateTableBody(pageInfo); // 在頁面上的表格中tfoot標籤內顯示分頁的頁碼導航條 initPagination(pageInfo); }
獲取分頁數據前端
function getPageInfo() { // 以同步請求方式調用$.ajax()函數並獲取返回值(返回值包含所有響應數據) var ajaxResult = $.ajax({ "url": "role/search/by/keyword.action", "type": "post", "data": { "pageNum": (window.pageNum == undefined) ? 1 : window.pageNum, "pageSize": (window.pageSize == undefined) ? 5 : window.pageSize, "keyword": (window.keyword == undefined) ? "" : window.keyword }, "dataType": "json", "async": false // 爲了保證getPageInfo()函數可以在Ajax請求拿到響應後獲取PageInfo,須要設置爲同步操做 }); // 從所有響應數據中獲取JSON格式的響應體數據 var resultEntity = ajaxResult.responseJSON; // 從響應體數據中獲取result,判斷當前請求是否成功 var result = resultEntity.result; // 若是成功獲取PageInfo if (result == "SUCCESS") { return resultEntity.data; } if (result == "FAILED") { layer.msg(resultEntity.message); } return null; }
使用PageInfo數據在tbody標籤內顯示分頁數據java
function generateTableBody(pageInfo) { // 執行全部操做前先清空 $("#roleTableBody").empty(); //這個對應頁面的 <tbody id="roleTableBody"> </tbody> // 獲取數據集合 var list = pageInfo.list; // 判斷list是否有效 if (list == null || list.length == 0) { $("#roleTableBody").append("<tr><td colspan='4' style='text-align:center;'>沒有查詢到數據!</td></tr>"); return; } for (var i = 0; i < list.length; i++) { var role = list[i]; var checkBtn = "<button type='button' class='btn btn-success btn-xs'><i class=' glyphicon glyphicon-check'></i></button>"; var pencilBtn = "<button type='button' id='roleTableBody' roleid='" + role.id + "' class='btn btn-primary btn-xs editBtn'><i class=' glyphicon glyphicon-pencil'></i></button>"; var removeBtn = "<button type='button' roleid='" + role.id + "' class='btn btn-danger btn-xs removeBtn'><i class=' glyphicon glyphicon-remove'></i></button>"; var numberTd = "<td>" + (i + 1) + "</td>"; var checkBoxTd = "<td><input class='itemBox' roleid='" + role.id + "' type='checkbox'></td>"; var roleNameTd = "<td>" + role.name + "</td>"; var btnTd = "<td>" + checkBtn + " " + pencilBtn + " " + removeBtn + "</td>"; var tr = "<tr>" + numberTd + checkBoxTd + roleNameTd + btnTd + "</tr>"; // 將前面拼好的HTML代碼追加到#roleTableBody中 $("#roleTableBody").append(tr); } }
聲明函數封裝導航條初始化操做jquery
function initPagination(pageInfo) { // 聲明變量存儲分頁導航條顯示時的屬性設置 var paginationProperties = { num_edge_entries: 3, //邊緣頁數 num_display_entries: 5, //主體頁數 callback: pageselectCallback, //回調函數 items_per_page: window.pageSize, //每頁顯示數據數量,就是pageSize current_page: (window.pageNum - 1),//當前頁頁碼 prev_text: "上一頁", //上一頁文本 next_text: "下一頁" //下一頁文本 }; // 顯示分頁導航條 <div id="Pagination" class="pagination"> <!-- 這裏顯示分頁 --> </div> $("#Pagination").pagination(pageInfo.total, paginationProperties); }
在每一次點擊「上一頁」、「下一頁」、「頁碼」時執行這個函數跳轉頁面git
function pageselectCallback(pageIndex, jq) { // 將全局變量中的pageNum修改成最新值 // pageIndex從0開始,pageNum從1開始 window.pageNum = pageIndex + 1; // 調用分頁函數從新執行分頁 showPage(); return false; }
頁面初始化,就是咱們點擊角色維護頁面須要加載的內容github
$(function(){ // 調用分頁參數初始化方法 initGlobalVariable(); // 執行分頁 showPage(); });
在點擊「查詢」按鈕後,獲取文本框中填寫的keyword值,賦值給全局變量keyword,調用showPage()函數便可。ajax
//關鍵字查詢實現 $("#searchBtn").click(function () { //獲取關鍵字查詢的值 var keywordInput = $.trim($("#keywordInput").val()); /*if (keywordInput==null || keywordInput==""){ layer.msg("請輸入關鍵詞"); return; }*/ window.keyword = keywordInput; //執行查詢操做 showPage(); });
點擊角色維護加載頁面數據兩種思路:spring
第一種是咱們請求後臺把查詢到的數據放到Model,前臺遍歷把數據展現出來。
第二種是咱們請求後臺把查詢到的數據當PageInfo<Role>,而後動態的拼接把數據展現到頁面上。(咱們採用第二種)
@ResponseBody @RequestMapping("/role/search/by/keyword") public ResultEntity<PageInfo<Role>> search( @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize, @RequestParam(value = "keyword", defaultValue = "") String keyword) { // 1.查詢獲得PageInfo對象 PageInfo<Role> pageInfo = roleService.queryForKeywordWithPage(pageNum, pageSize, keyword); // 2.封裝結果對象返回 return ResultEntity.successWithData(pageInfo); }
public PageInfo<Role> queryForKeywordWithPage(Integer pageNum, Integer pageSize, String keyword) { // 1.開啓分頁功能 PageHelper.startPage(pageNum, pageSize); // 2.執行查詢 List<Role> list = roleMapper.selectForKeywordSearch(keyword); // 3.封裝爲PageInfo對象 return new PageInfo<Role>(list); }
List<Role> selectForKeywordSearch(String keyword);
Mapper.xml
<select id="selectForKeywordSearch" resultMap="BaseResultMap"> SELECT id, `name` FROM t_role WHERE `name` LIKE CONCAT('%', #{keyword}, '%') </select>
role-page.jsp
<thead> <tr> <th width="30">#</th> <th width="30"><input id="summaryBox" type="checkbox"></th> <th>名稱</th> <th width="100">操做</th> </tr> </thead>
my-role.js
for (var i = 0; i < list.length; i++) { //省略 var checkBoxTd = "<td><input class='itemBox' roleid='" + role.id + "' type='checkbox'></td>"; //省略 }
//全選/全不選功能實現 $("#summaryBox").click(function () { //獲取當前的選中狀態 var currentStatus = this.checked; $(".itemBox").prop("checked", currentStatus); });
先準備模態框的HTML標籤,include-modal-role-confirm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <div id="confirmModal" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> <h4 class="modal-title">角色維護刪除</h4> </div> <div class="modal-body"> <p>您肯定要刪除下面的顯示的內容嗎?</p> <table class="table table-bordered"> <thead> <tr> <th width="30">#</th> <th>名稱</th> </tr> </thead> <tbody id="confirmModalTableBody"></tbody> </table> </div> <div class="modal-footer"> <button id="confirmModalBtn" type="button" class="btn btn-primary">OK</button> </div> </div> </div> </div>
在role-page.jsp中包含include-modal-role-confirm.jsp文件, <%@ include file="/WEB-INF/include-modal-role-confirm.jsp" %>
//id查詢角色信息 function getRoleListByRoleIdArray(roleIdArray) { //roleIdArray轉換成JSON字符串 var roleIds = JSON.stringify(roleIdArray); var ajaxResult = $.ajax({ "url": "role/get/list/by/id/list.action", "type": "post", "data": roleIds, "contentType": "application/json;charset=UTF-8", "dataType": "json", "async": false }); // 3.獲取JSON對象類型的響應體 var resultEntity = ajaxResult.responseJSON; var result = resultEntity.result; if (result == "SUCCESS") { // 5.若是成功,則返回roleList return resultEntity.data; } if (result == "FAILED") { layer.msg(resultEntity.message); return null; } return null; }
對應的後端代碼:
@ResponseBody @RequestMapping("role/get/list/by/id/list") public ResultEntity<List<Role>> getRoleListByIdList(@RequestBody List<Integer> roleIds) { List<Role> roleList = roleService.findRoleListByIdList(roleIds); return ResultEntity.successWithData(roleList); }
public List<Role> findRoleListByIdList(List<Integer> roleIds) { return roleMapper.findRoleListByIdList(roleIds); }
// 打開刪除確認模態框 function showRemoveConfirmModal() { // 1.將模態框顯示出來 $("#confirmModal").modal("show"); //獲取角色數據 var roleList = getRoleListByRoleIdArray(window.roleIdArray); //清空表格數據 $("#confirmModalTableBody").empty(); //填充confirmModalTableBody的數據 for (var i = 0; i < roleList.length; i++) { // 5.獲取角色相關數據 var role = roleList[i]; var id = role.id; var name = role.name; var trHTML = "<tr><td>" + (i+1) + "</td><td>" + name + "</td></tr>"; // 6.執行填充 $("#confirmModalTableBody").append(trHTML); } }
<button type="button" class="btn btn-danger" id="batchRemoveBtn" style="float: right; margin-left: 10px;"> <i class=" glyphicon glyphicon-remove"></i> 刪除 </button>
// 給批量刪除按鈕綁定單擊響應函數 $("#batchRemoveBtn").click(function () { //獲取被選中的itemBox數組長度 var length = $(".itemBox:checked").length; if (length == 0) { layer.msg("請選擇要刪除的記錄!!"); return; } // 未完待續... });
// 給批量刪除按鈕綁定單擊響應函數 $("#batchRemoveBtn").click(function () { //獲取被選中的itemBox數組長度 var length = $(".itemBox:checked").length; if (length == 0) { layer.msg("請選擇要刪除的記錄!!"); return; } window.roleIdArray = new Array(); //遍歷複選框 $(".itemBox:checked").each(function () { //經過checkbox的roleid屬性獲取roleId值 var roleId = $(this).attr("roleid"); //存入數組 window.roleIdArray.push(roleId); }); // 調用函數打開模態框 showRemoveConfirmModal(); });
<button **id="confirmModalBtn"** type="button" class="btn btn-primary">OK</button>
$("#confirmModalBtn").click(function () { //數組轉成Json var roleIds = JSON.stringify(window.roleIdArray); var ajaxResult = $.ajax({ "url": "role/batch/remove.action", "type": "post", "data": roleIds, "contentType": "application/json;charset=UTF-8", "dataType": "json", "async": false, "success": function (response) { var result = response.result; if (result == "SUCCESS") { layer.msg("操做成功!"); // 若是刪除成功,則從新調用分頁方法 showPage(); } if (result == "FAILED") { layer.msg(response.message); } // 無論成功仍是失敗,都須要關掉模態框 $("#confirmModal").modal("hide"); }, "error": function (response) { if (result == "FAILED") { layer.msg(response.message); } } }); });
@ResponseBody @RequestMapping(value = "role/batch/remove") public ResultEntity<String> batchAdminList(@RequestBody List<Integer> roleIds) { try { roleService.batchRoleList(roleIds); return ResultEntity.successWithoutData(); } catch (Exception e) { return ResultEntity.failed(null, e.getMessage()); } }
public void batchRoleList(List<Integer> roleIds) { roleMapper.batchRoleList(roleIds); }
<delete id="batchRoleList" parameterType="java.util.List"> delete from t_role where id in <foreach collection="list" item="item" open="(" separator="," close=")" > #{item} </foreach> </delete>
<button type="button" class="btn btn-primary" id="addBtn" style="float: right;"> <i class="glyphicon glyphicon-plus"></i> 新增 </button>
$("#addBtn").click(function(){ alert("aaa..."); });
先準備模態框的HTML代碼,include-modal-role-add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <div id="addModal" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <form role="form"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> <h4 class="modal-title">角色添加</h4> </div> <div class="modal-body"> <input type="text" id="roleNameInput" class="form-control" placeholder="請輸入角色名稱" /> </div> <div class="modal-footer"> <button type="button" id="addModalBtn" class="btn btn-default"><i class="glyphicon glyphicon-plus"></i> 保存</button> <button type="reset" class="btn btn-primary"><i class="glyphicon glyphicon-refresh"></i> 重置</button> </div> </form> </div> </div> </div>
將include-modal-role-add.jsp包含到role-page.jsp , <%@ include file="/WEB-INF/include-modal-role-add.jsp" %>
$("#addBtn").click(function(){ $("#addModal").modal("show"); });
<button id="addModalBtn" type="button" class="btn btn-success"> <i class="glyphicon glyphicon-plus"></i>保存 </button>
$("#addModalBtn").click(function () { // 1.收集文本框內容 var roleName = $.trim($("#roleNameInput").val()); if (roleName == null || roleName == "") { layer.msg("請輸入有效角色名稱!"); return; } // 2.發送請求 $.ajax({ "url": "role/save/role.action", "type": "post", "data": { "roleName": roleName }, "dataType": "json", "success": function (response) { var result = response.result; if (result == "SUCCESS") { layer.msg("操做成功!"); // 3.操做成功從新分頁 // 前往最後一頁 window.pageNum = 999999; showPage(); } if (result == "FAILED") { layer.msg(response.message); } // 4.無論成功仍是失敗,關閉模態框 $("#addModal").modal("hide"); // 5.清理本次在文本框填寫的數據 $("#roleNameInput").val(""); }, "error": function (response) { layer.msg(response.message); } }); });
@ResponseBody @RequestMapping("role/save/role") public ResultEntity<String> saveRole(@RequestParam("roleName") String roleName) { try { roleService.saveRole(roleName); return ResultEntity.successWithoutData(); } catch (Exception e) { return ResultEntity.failed(null, e.getMessage()); } }
公共返回代碼
public class ResultEntity<T> { public static final String SUCCESS = "SUCCESS"; public static final String FAILED = "FAILED"; public static final String NO_MESSAGE = "NO_MESSAGE"; public static final String NO_DATA = "NO_DATA"; // 方便返回成功結果(不攜帶查詢結果狀況) public static ResultEntity<String> successWithoutData() { return new ResultEntity<String>(SUCCESS, NO_MESSAGE, NO_DATA); } // 方便返回成功結果(攜帶查詢結果狀況) public static <E> ResultEntity<E> successWithData(E data) { return new ResultEntity<E>(SUCCESS, NO_MESSAGE, data); } // 方便返回失敗結果 public static <E> ResultEntity<E> failed(E data, String message) { return new ResultEntity<E>(FAILED, message, data); } private String result; private String message; private T data; public ResultEntity() { } public ResultEntity(String result, String message, T data) { super(); this.result = result; this.message = message; this.data = data; } @Override public String toString() { return "ResultEntity [result=" + result + ", message=" + message + ", data=" + data + "]"; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
給編輯按鈕綁定單擊響應函數
打開模態框
my-role.js文件
function generateTableBody(pageInfo) { //省略 var pencilBtn = "<button type='button' roleid='" + role.id + "' class='btn btn-primary btn-xs editBtn'><i class=' glyphicon glyphicon-pencil'></i></button>"; //省略 } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> <div id="editModal" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog" role="document"> <div class="modal-content"> <form role="form"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> <h4 class="modal-title">尚籌網系統彈窗</h4> </div> <div class="modal-body"> <input type="text" id="roleNameInputEdit" class="form-control" placeholder="請輸入角色名稱" /> </div> <div class="modal-footer"> <button id="editModalBtn" type="button" class="btn btn-warning"> <i class="glyphicon glyphicon-edit"></i> 更新 </button> <button type="reset" class="btn btn-primary"> <i class="glyphicon glyphicon-refresh"></i> 重置 </button> </div> </form> </div> </div> </div>
將include-modal-role-add.jsp包含到role-page.jsp , <%@ include file="/WEB-INF/include-modal-role-edit.jsp" %>
$("#roleTableBody").on("click", ".editBtn", function () { // 1.獲取當前按鈕的roleId window.roleId = $(this).attr("roleId"); // 2.獲取當前按鈕所在行的roleName var roleName = $(this).parents("tr").children("td:eq(2)").text(); // 3.修改模態框中文本框的value值,目的是在顯示roleName $("#roleNameInputEdit").val(roleName); // 4.打開模態框 $("#editModal").modal("show"); });
$("#editModalBtn").click(function () { // 1.獲取文本框值 var roleName = $.trim($("#roleNameInputEdit").val()); if (roleName == null || roleName == "") { layer.msg("請輸入有效角色名稱!"); return; } // 2.發送請求 $.ajax({ "url": "role/update.action", "type": "post", "data": { "id": window.roleId, "name": roleName }, "dataType": "json", "success": function (response) { var result = response.result; if (result == "SUCCESS") { layer.msg("操做成功!"); // 3.操做成功從新分頁 showPage(); } if (result == "FAILED") { layer.msg(response.message); } // 4.無論成功仍是失敗,關閉模態框 $("#editModal").modal("hide"); } }); });
@ResponseBody @RequestMapping("role/update") public ResultEntity<String> updateRole(@RequestParam("id") Integer id, @RequestParam("name") String name) { Role role = new Role(); role.setId(id); role.setName(name); try { roleService.updateRole(role); return ResultEntity.successWithoutData(); } catch (Exception e) { return ResultEntity.failed(null, e.getMessage()); } }
Ajax請求在服務器端處理過程當中拋出異常,通過異常處理器:
@ControllerAdvice public class CrowdFundingExceptionResolever { @ExceptionHandler(value=Exception.class) public ModelAndView catchException(Exception exception) { ModelAndView mav = new ModelAndView(); mav.addObject("exception", exception); mav.setViewName("system-error"); return mav; } }
目前這個異常處理機制,只能返回頁面,而不能針對Ajax請求返回JSON格式的響應數據。因此Ajax請求處理過程當中,若是拋出異常,返回異常信息頁面,Ajax程序沒法正常解析,致使頁面不能正常顯示和工做,也不能給出友好的錯誤提示。
/** * 用於判斷一個請求是不是異步請求 * @param request * @return */ public static boolean checkAsyncRequest(HttpServletRequest request) { // 1.獲取相應請求消息頭 String accept = request.getHeader("Accept"); String xRequested = request.getHeader("X-Requested-With"); // 2.判斷請求消息頭數據中是否包含目標特徵 if( (stringEffective(accept) && accept.contains("application/json")) || (stringEffective(xRequested) && xRequested.contains("XMLHttpRequest")) ) { return true; } return false; } /** * 判斷字符串是否有效 * @param source 待驗證字符串 * @return true表示有效,false表示無效 */ public static boolean stringEffective(String source) { return source != null && source.length() > 0; }
首先引入:
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.5</version> </dependency>
@ControllerAdvice public class CrowdFundingExceptionResolever { @ExceptionHandler(value = Exception.class) public ModelAndView catchException( Exception exception, HttpServletRequest request, HttpServletResponse response) throws IOException { // 1.對當前請求進行檢查 boolean checkAsyncRequestResult = CrowdFundingUtils.checkAsyncRequest(request); // 2.若是是異步請求 if(checkAsyncRequestResult) { // 根據異常類型在常量中的映射,使用比較友好的文字顯示錯誤提示消息 String exceptionClassName = exception.getClass().getName(); String message = CrowdFundingConstant.EXCEPTION_MESSAGE_MAP.get(exceptionClassName); if(message == null) { message = "系統未知錯誤"; } // 3.建立ResultEntity對象 ResultEntity<String> resultEntity = ResultEntity.failed(ResultEntity.NO_DATA, message); // 4.將resultEntity轉換爲JSON格式 Gson gson = new Gson(); String json = gson.toJson(resultEntity); // 5.將json做爲響應數據返回給瀏覽器 response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(json); return null; } ModelAndView mav = new ModelAndView(); mav.addObject("exception", exception); mav.setViewName("system-error"); return mav; } }
常量類
public class CrowdFundingConstant { public static final Map<String, String> EXCEPTION_MESSAGE_MAP = new HashMap<String, String>(); static { EXCEPTION_MESSAGE_MAP.put("java.lang.ArithmeticException", "系統在進行數學運算時發生錯誤"); EXCEPTION_MESSAGE_MAP.put("java.lang.RuntimeException", "系統在運行時發生錯誤"); EXCEPTION_MESSAGE_MAP.put("com.atguigu.crowd.funding.exception.LoginException", "登陸過程當中運行錯誤"); } }
我是阿福,公衆號「阿福聊編程」做者,對後端技術保持學習愛好者,我會常常更新JAVA技術文章,在進階的路上,共勉!