溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么實現(xiàn)JavaWeb用戶的增刪改查

發(fā)布時間:2021-10-29 17:16:42 來源:億速云 閱讀:211 作者:iii 欄目:編程語言

本篇內(nèi)容介紹了“怎么實現(xiàn)JavaWeb用戶的增刪改查”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

準備工作

后端技術(shù)

怎么實現(xiàn)JavaWeb用戶的增刪改查

前端技術(shù)

怎么實現(xiàn)JavaWeb用戶的增刪改查

角色維護-分頁實現(xiàn)

分頁前端功能實現(xiàn)

怎么實現(xiàn)JavaWeb用戶的增刪改查

創(chuàng)建外部JavaScript源文件,role.js

在頁面 role-page.jsp引入role.js文件

<script type="text/javascript" src="script/my-role.js"></script>

初始化全局函數(shù)

分頁實現(xiàn)初始化全局函數(shù),每頁的條數(shù),頁碼,模糊查詢的關(guān)鍵詞

//初始化全局變量  function initGlobalVariable() {      window.pageSize = 5; //每頁的條數(shù)      window.pageNum = 1;  //頁碼      window.keyword = ""; //關(guān)鍵詞  }

聲明分頁函數(shù)

//給服務器發(fā)送請求獲取分頁數(shù)據(jù)(pageInfo),并在頁面上顯示分頁效果(主體、頁碼導航條)  function showPage() {      // 給服務器發(fā)送請求獲取分頁數(shù)據(jù):PageInfo      var pageInfo = getPageInfo();      // 在頁面上的表格中tbody標簽內(nèi)顯示分頁的主體數(shù)據(jù)      generateTableBody(pageInfo);      // 在頁面上的表格中tfoot標簽內(nèi)顯示分頁的頁碼導航條      initPagination(pageInfo);  }

獲取分頁數(shù)據(jù)

function getPageInfo() {      // 以同步請求方式調(diào)用$.ajax()函數(shù)并獲取返回值(返回值包含全部響應數(shù)據(jù))      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()函數(shù)能夠在Ajax請求拿到響應后獲取PageInfo,需要設置為同步操作      });       // 從全部響應數(shù)據(jù)中獲取JSON格式的響應體數(shù)據(jù)      var resultEntity = ajaxResult.responseJSON;      // 從響應體數(shù)據(jù)中獲取result,判斷當前請求是否成功      var result = resultEntity.result;      // 如果成功獲取PageInfo      if (result == "SUCCESS") {          return resultEntity.data;      }      if (result == "FAILED") {          layer.msg(resultEntity.message);      }      return null;  }

使用PageInfo數(shù)據(jù)在tbody標簽內(nèi)顯示分頁數(shù)據(jù)

function generateTableBody(pageInfo) {      // 執(zhí)行所有操作前先清空      $("#roleTableBody").empty();   //這個對應頁面的 <tbody id="roleTableBody"> </tbody>      // 獲取數(shù)據(jù)集合      var list = pageInfo.list;      // 判斷l(xiāng)ist是否有效      if (list == null || list.length == 0) {          $("#roleTableBody").append("<tr><td colspan='4' style='text-align:center;'>沒有查詢到數(shù)據(jù)!</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);      }  }

聲明函數(shù)封裝導航條初始化操作

function initPagination(pageInfo) {      // 聲明變量存儲分頁導航條顯示時的屬性設置      var paginationProperties = {          num_edge_entries: 3,            //邊緣頁數(shù)          num_display_entries: 5,        //主體頁數(shù)          callback: pageselectCallback,    //回調(diào)函數(shù)          items_per_page: window.pageSize,    //每頁顯示數(shù)據(jù)數(shù)量,就是pageSize          current_page: (window.pageNum - 1),//當前頁頁碼          prev_text: "上一頁",            //上一頁文本          next_text: "下一頁"            //下一頁文本      };      // 顯示分頁導航條 <div id="Pagination" class="pagination"> <!-- 這里顯示分頁 --> </div>      $("#Pagination").pagination(pageInfo.total, paginationProperties);  }

在每一次點擊“上一頁”、“下一頁”、“頁碼”時執(zhí)行這個函數(shù)跳轉(zhuǎn)頁面

function pageselectCallback(pageIndex, jq) {      // 將全局變量中的pageNum修改為最新值      // pageIndex從0開始,pageNum從1開始      window.pageNum = pageIndex + 1;      // 調(diào)用分頁函數(shù)重新執(zhí)行分頁      showPage();      return false;  }

頁面初始化,就是我們點擊角色維護頁面需要加載的內(nèi)容

$(function(){          // 調(diào)用分頁參數(shù)初始化方法      initGlobalVariable();      // 執(zhí)行分頁      showPage();  });

關(guān)鍵詞查詢功能

在點擊“查詢”按鈕后,獲取文本框中填寫的keyword值,賦值給全局變量keyword,調(diào)用showPage()函數(shù)即可。

//關(guān)鍵字查詢實現(xiàn)          $("#searchBtn").click(function () {              //獲取關(guān)鍵字查詢的值              var keywordInput = $.trim($("#keywordInput").val());              /*if (keywordInput==null || keywordInput==""){                  layer.msg("請輸入關(guān)鍵詞");                  return;              }*/              window.keyword = keywordInput;              //執(zhí)行查詢操作              showPage();          });

分頁后端實現(xiàn)

點擊角色維護加載頁面數(shù)據(jù)兩種思路:

第一種是我們請求后臺把查詢到的數(shù)據(jù)放到Model,前臺遍歷把數(shù)據(jù)展示出來。

第二種是我們請求后臺把查詢到的數(shù)據(jù)當PageInfo<Role>,然后動態(tài)的拼接把數(shù)據(jù)展示到頁面上。(我們采用第二種)

Controller方法的實現(xiàn)

@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.封裝結(jié)果對象返回          return ResultEntity.successWithData(pageInfo);      }

Service方法的實現(xiàn)

public PageInfo<Role> queryForKeywordWithPage(Integer pageNum, Integer pageSize, String keyword) {          // 1.開啟分頁功能          PageHelper.startPage(pageNum, pageSize);         // 2.執(zhí)行查詢          List<Role> list = roleMapper.selectForKeywordSearch(keyword);          // 3.封裝為PageInfo對象          return new PageInfo<Role>(list);      }

Mapper方法的實現(xiàn)

List<Role> selectForKeywordSearch(String keyword);

Mapper.xml

<select id="selectForKeywordSearch" resultMap="BaseResultMap">          SELECT              id,              `name`          FROM              t_role          WHERE              `name` LIKE CONCAT('%', #{keyword}, '%')  </select>

角色維護-全選功能

功能在頁面的位置

怎么實現(xiàn)JavaWeb用戶的增刪改查

具體實現(xiàn)

標記

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綁定單擊響應函數(shù) 

//全選/全不選功能實現(xiàn)   $("#summaryBox").click(function () {              //獲取當前的選中狀態(tài)              var currentStatus = this.checked;              $(".itemBox").prop("checked", currentStatus);   });

角色維護-批量刪除

準備模態(tài)框

先準備模態(tài)框的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">&times;</span>                  </button>                  <h5 class="modal-title">角色維護刪除</h5>              </div>              <div class="modal-body">                  <p>您確定要刪除下面的顯示的內(nèi)容嗎?</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" %>

getRoleListByRoleIdArray()函數(shù)

//id查詢角色信息  function getRoleListByRoleIdArray(roleIdArray) {      //roleIdArray轉(zhuǎn)換成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);      }

showRemoveConfirmModal()函數(shù)

// 打開刪除確認模態(tài)框  function showRemoveConfirmModal() {      // 1.將模態(tài)框顯示出來     $("#confirmModal").modal("show");      //獲取角色數(shù)據(jù)      var roleList = getRoleListByRoleIdArray(window.roleIdArray);      //清空表格數(shù)據(jù)      $("#confirmModalTableBody").empty();      //填充confirmModalTableBody的數(shù)據(jù)      for (var i = 0; i < roleList.length; i++) {          // 5.獲取角色相關(guān)數(shù)據(jù)          var role = roleList[i];          var id = role.id;          var name = role.name;          var trHTML = "<tr><td>" + (i+1) + "</td><td>" + name + "</td></tr>";          // 6.執(zhí)行填充          $("#confirmModalTableBody").append(trHTML);      }  }

點擊批量刪除按鈕綁定單擊響應函數(shù)

標記批量刪除按鈕

<button type="button" class="btn btn-danger" id="batchRemoveBtn"                              style="float: right; margin-left: 10px;">                          <i class=" glyphicon glyphicon-remove"></i> 刪除   </button>

檢查itemBox是否被選中

// 給批量刪除按鈕綁定單擊響應函數(shù)          $("#batchRemoveBtn").click(function () {              //獲取被選中的itemBox數(shù)組長度              var length = $(".itemBox:checked").length;              if (length == 0) {                  layer.msg("請選擇要刪除的記錄??!");                  return;              }             // 未完待續(xù)...          });

在彈出的模態(tài)框中顯示confirm信息

怎么實現(xiàn)JavaWeb用戶的增刪改查

// 給批量刪除按鈕綁定單擊響應函數(shù)         $("#batchRemoveBtn").click(function () {             //獲取被選中的itemBox數(shù)組長度             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");                 //存入數(shù)組                 window.roleIdArray.push(roleId);             });             // 調(diào)用函數(shù)打開模態(tài)框             showRemoveConfirmModal();         });

點擊模態(tài)框的OK按鈕執(zhí)行刪除

標記OK按

<button **id="confirmModalBtn"** type="button" class="btn btn-primary">OK</button>

綁定單擊響應函數(shù)

$("#confirmModalBtn").click(function () {              //數(shù)組轉(zhuǎn)成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("操作成功!");                          // 如果刪除成功,則重新調(diào)用分頁方法                          showPage();                      }                      if (result == "FAILED") {                          layer.msg(response.message);                      }                      // 不管成功還是失敗,都需要關(guān)掉模態(tài)框                      $("#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>

角色維護-新增

大體步驟

  • 給“新增”按鈕綁定單擊響應函數(shù)

  • 打開模態(tài)框

  • 給“保存”按鈕綁定單擊響應函數(shù)

  • 收集文本框內(nèi)容

  • 發(fā)送請求

  • 請求處理完成關(guān)閉模態(tài)框、重新分頁、清理表單

給新增按鈕綁定單擊響應函數(shù)

標記新增按鈕

<button type="button" class="btn btn-primary" id="addBtn"                             style="float: right;">                         <i class="glyphicon glyphicon-plus"></i> 新增  </button>

綁定單擊響應函數(shù)

$("#addBtn").click(function(){ alert("aaa..."); });

準備模態(tài)框

先準備模態(tài)框的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">&times;</span>                      </button>                      <h5 class="modal-title">角色添加</h5>                  </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" %>

打開模態(tài)框

$("#addBtn").click(function(){ $("#addModal").modal("show"); });

給“保存”按鈕綁定單擊響應函數(shù)

標記“保存”按鈕

<button id="addModalBtn" type="button" class="btn btn-success"> <i class="glyphicon glyphicon-plus"></i>保存 </button>

綁定單擊響應函數(shù)

$("#addModalBtn").click(function () {              // 1.收集文本框內(nèi)容              var roleName = $.trim($("#roleNameInput").val());              if (roleName == null || roleName == "") {                  layer.msg("請輸入有效角色名稱!");                  return;              }              // 2.發(fā)送請求              $.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.不管成功還是失敗,關(guān)閉模態(tài)框                      $("#addModal").modal("hide");                      // 5.清理本次在文本框填寫的數(shù)據(jù)                      $("#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";      // 方便返回成功結(jié)果(不攜帶查詢結(jié)果情況)      public static ResultEntity<String> successWithoutData() {          return new ResultEntity<String>(SUCCESS, NO_MESSAGE, NO_DATA);      }      // 方便返回成功結(jié)果(攜帶查詢結(jié)果情況)      public static <E> ResultEntity<E> successWithData(E data) {          return new ResultEntity<E>(SUCCESS, NO_MESSAGE, data);      }      // 方便返回失敗結(jié)果      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;      }  }

角色維護-更新

大體步驟

給編輯按鈕綁定單擊響應函數(shù)

打開模態(tài)框

  • 準備模態(tài)框

  • 把roleId保存到全局變量

  • 獲取到當前按鈕所在行的roleName

  • 使用roleName回顯模態(tài)框中的表單

  • 給“更新”按鈕綁定單擊響應函數(shù)

  • 收集文本框內(nèi)容

  • 發(fā)送請求

  • 請求處理完成關(guān)閉模態(tài)框、重新分頁

給編輯按鈕綁定單擊響應函數(shù)

標記編輯按鈕

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>";        //省略      }  }

準備模態(tài)框

<%@ 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">&times;</span>                      </button>                      <h5 class="modal-title">尚籌網(wǎng)系統(tǒng)彈窗</h5>                  </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" %>

綁定單擊響應函數(shù)

$("#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.修改模態(tài)框中文本框的value值,目的是在顯示roleName             $("#roleNameInputEdit").val(roleName);             // 4.打開模態(tài)框             $("#editModal").modal("show");         });

給“更新”按鈕綁定單擊響應函數(shù)

$("#editModalBtn").click(function () {              // 1.獲取文本框值              var roleName = $.trim($("#roleNameInputEdit").val());              if (roleName == null || roleName == "") {                  layer.msg("請輸入有效角色名稱!");                  return;              }              // 2.發(fā)送請求              $.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.不管成功還是失敗,關(guān)閉模態(tài)框                      $("#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());          }      }

異常映射兼容異步請求

問題表現(xiàn)

Ajax請求在服務器端處理過程中拋出異常,經(jīng)過異常處理器:

@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格式的響應數(shù)據(jù)。所以Ajax請求處理過程中,如果拋出異常,返回異常信息頁面,Ajax程序無法正常解析,導致頁面不能正常顯示和工作,也不能給出友好的錯誤提示。

問題解決思路

怎么實現(xiàn)JavaWeb用戶的增刪改查

異步請求特點

怎么實現(xiàn)JavaWeb用戶的增刪改查

分辨異步請求的工具方法 

/**       * 用于判斷一個請求是否是異步請求       * @param request       * @return       */      public static boolean checkAsyncRequest(HttpServletRequest request) {                // 1.獲取相應請求消息頭          String accept = request.getHeader("Accept");          String xRequested = request.getHeader("X-Requested-With");                 // 2.判斷請求消息頭數(shù)據(jù)中是否包含目標特征          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) {              // 根據(jù)異常類型在常量中的映射,使用比較友好的文字顯示錯誤提示消息              String exceptionexceptionClassName = exception.getClass().getName();             String message = CrowdFundingConstant.EXCEPTION_MESSAGE_MAP.get(exceptionClassName);              if(message == null) {                  message = "系統(tǒng)未知錯誤";              }              // 3.創(chuàng)建ResultEntity對象              ResultEntity<String> resultEntity = ResultEntity.failed(ResultEntity.NO_DATA, message);              // 4.將resultEntity轉(zhuǎn)換為JSON格式              Gson gson = new Gson();              String json = gson.toJson(resultEntity);              // 5.將json作為響應數(shù)據(jù)返回給瀏覽器              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", "系統(tǒng)在進行數(shù)學運算時發(fā)生錯誤");          EXCEPTION_MESSAGE_MAP.put("java.lang.RuntimeException", "系統(tǒng)在運行時發(fā)生錯誤");          EXCEPTION_MESSAGE_MAP.put("com.atguigu.crowd.funding.exception.LoginException", "登錄過程中運行錯誤");      }  }

“怎么實現(xiàn)JavaWeb用戶的增刪改查”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI