preface

This paper is based on the function of adding, deleting, changing and checking the role of the single architecture. The front end uses Bootstrap+Ajax+Jsp, and the back end uses Spring+SpringMvc+MyBatis for development. I believe that those who have used these technologies should have a good understanding of the following content, and ALSO hope to read this article.

The preparatory work

The back-end technology

technology instructions website
Spring Spring is a lightweight Inversion of Control (IoC) and AOP oriented container framework. spring.io/
SpringMvc The MVC framework https://spring.io/projects/spring-boot
MyBatis Persistence layer frame https://mybatis.org/mybatis-3/zh/index.html
Druid Database connection pool https://github.com/alibaba/druid
log4j The logging framework https://logging.apache.org/log4j/2.x/

The front-end technology

Bootstrap Simple, intuitive, powerful front-end development framework https://www.bootcss.com/
Ajax Front and back end interaction https://www.w3school.com.cn/ajax/index.asp
Jsp A template engine https://www.runoob.com/jsp/jsp-intro.html
layer.js Message prompt http://www.h-ui.net/lib/layer.js.shtml
Modal plug-in A Modal box is a child form overlaid on top of a parent form https://www.runoob.com/bootstrap/bootstrap-modal-plugin.html
jquery.pagination.js Paging plug-in http://www.jq22.com/yanshi5697/

Role maintenance – Paging implementation

Paging front end function realization


Create an external JavaScript source file, role-.js

Introduce the role-.js file in the role-page.jsp page

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

Initialize the global function

Paging implements initialization of global functions, number of pages per page, page number, fuzzy query keywords

// Initialize the global variable
function initGlobalVariable() {
    window.pageSize = 5; // The number of items per page
    window.pageNum = 1;  / / page
    window.keyword = ""; / / keywords
} Copy the code

Declare paging functions

// Send a request to the server for paging data (pageInfo), and display the paging effect on the page (body, page number navigation bar)
function showPage() {

    // Send a request to the server for paging data: PageInfo
    var pageInfo = getPageInfo();
  Display paginated body data in the tBody TAB in the table on the page  generateTableBody(pageInfo);   // Displays the paginated page number navigation bar in the tfoot TAB in the table on the page  initPagination(pageInfo); } Copy the code

Get paging data

function getPageInfo() {

    // Call $.ajax() as a synchronous request and get the return value (the return value contains all the response data)
    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 // To ensure that the getPageInfo() function gets PageInfo after the Ajax request gets the response, it needs to be set to synchronous  });   // Get the response body data in JSON format from the entire response data  var resultEntity = ajaxResult.responseJSON;   // Obtain the result from the response body data to determine whether the current request was successful  var result = resultEntity.result;   // If successfully get PageInfo  if (result == "SUCCESS") {  return resultEntity.data;  }   if (result == "FAILED") {  layer.msg(resultEntity.message);  }   return null; } Copy the code

Use PageInfo data to display paging data within the TBody tag

function generateTableBody(pageInfo) {
    // Clean up before performing any operations
    $("#roleTableBody").empty();    
    // Get the data set
    var list = pageInfo.list;
  // Check whether the list is valid  if (list == null || list.length == 0) {  $("#roleTableBody").append(" < span style = "max-width: 100%; ");  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>";   // Append the previously spelled HTML code to #roleTableBody  $("#roleTableBody").append(tr);  } } Copy the code

Declarative functions encapsulate navigation bar initialization operations

function initPagination(pageInfo) {

    // Declare the variable to store the properties displayed in the paging navigation bar
    var paginationProperties = {
        num_edge_entries: 3.// Number of edge pages
 num_display_entries: 5.// Number of main pages  callback: pageselectCallback, // The callback function  items_per_page: window.pageSize, // Display the number of data per page, which is pageSize  current_page: (window.pageNum - 1),// The current page number  prev_text: "Previous page".// Previous page of text  next_text: "Next page" // Next page of text  };   <div id="Pagination" class=" Pagination" > <! </div>  $("#Pagination").pagination(pageInfo.total, paginationProperties); } Copy the code

Execute this function to jump to a page each time you click on Previous, Next, or Page number

function pageselectCallback(pageIndex, jq) {

    // Change the pageNum in the global variable to the latest value
    // pageIndex starts at 0, pageNum starts at 1
    window.pageNum = pageIndex + 1;
  // Call the paging function to re-perform the paging  showPage();   return false; } Copy the code

Page initialization is what we need to load when we click on the character maintenance page

$(function(){
 
 // Call the paging parameter initialization method
 initGlobalVariable();
 // Perform paging
 showPage(); });  Copy the code

Keywords query function

After clicking the “query” button, get the keyword value filled in the text box, assign the value to the global variable keyword, and call the showPage() function.

// keyword query implementation
        $("#searchBtn").click(function () {
            // Get the value of the keyword query
            var keywordInput = $.trim($("#keywordInput").val());
            /*if (keywordInput==null || keywordInput==""){ Layer. MSG (" Please enter keywords "); return; } * /  window.keyword = keywordInput;  // Perform query operations  showPage();   }); Copy the code

Paging back end implementation

Click role maintenance to load page data in two ways:

In the first way, we request the background to put the queried data into the Model, and the foreground iterates and displays the data.

The second is that we request the background to query the data as PageInfo, and then dynamic Mosaic to display the data on the page. (We use the second option)

Implementation of the Controller method

@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. Query the PageInfo object  PageInfo<Role> pageInfo = roleService.queryForKeywordWithPage(pageNum, pageSize, keyword);   // 2. Encapsulate the result object return  return ResultEntity.successWithData(pageInfo);  } Copy the code

Implementation of the Service method

public PageInfo<Role> queryForKeywordWithPage(Integer pageNum, Integer pageSize, String keyword) {
  // 1. Enable paging
  PageHelper.startPage(pageNum, pageSize);

  // 2. Execute the query
 List<Role> list = roleMapper.selectForKeywordSearch(keyword);   // 3. Encapsulate as a PageInfo object  return new PageInfo<Role>(list);  } Copy the code

Mapper method implementation

List<Role> selectForKeywordSearch(String keyword);
Copy the code

Mapper.xml

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

Role maintenance – Select all functions

Function location on the page


The specific implementation

tag

role-page.jsp

<thead>
 <tr>
  <th width="30">#</th>
  <th width="30"><input id="summaryBox" type="checkbox"></th>
 <th>The name of the</th>  <th width="100">operation</th>  </tr> </thead> Copy the code

my-role.js

for (var i = 0; i < list.length; i++) {
        / / to omit
        var checkBoxTd = "<td><input class='itemBox' roleid='" + role.id + "' type='checkbox'></td>";
       / / to omit
}
Copy the code

Bind the summaryBox and click the response function

 // Select all/select none function implementation
 $("#summaryBox").click(function () {
            // Get the current selected state
            var currentStatus = this.checked;
            $(".itemBox").prop("checked", currentStatus);
 }); Copy the code

Maintaining roles – Deleting roles in batches

Prepare the modal box

Prepare the HTML tag for the modal box,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>  <h4 class="modal-title">Deleting a Role</h4>  </div>  <div class="modal-body">  <p>Are you sure you want to delete the following display?</p>  <table class="table table-bordered">  <thead>  <tr>  <th width="30">#</th>  <th>The name of the</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> Copy the code

<%@ include file=”/ web-INF /include-modal-role-confirm. JSP “%>

GetRoleListByRoleIdArray () function

//id Queries role information
function getRoleListByRoleIdArray(roleIdArray) {
    //roleIdArray converts to a JSON string
    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. Obtain the response body of the JSON object type  var resultEntity = ajaxResult.responseJSON;  var result = resultEntity.result;  if (result == "SUCCESS") {   // 5. If successful, return roleList  return resultEntity.data;  }   if (result == "FAILED") {  layer.msg(resultEntity.message);  return null;  }   return null;  } Copy the code

Corresponding back-end code:

 @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);
 } Copy the code
public List<Role> findRoleListByIdList(List<Integer> roleIds) {

  return roleMapper.findRoleListByIdList(roleIds);
 }
Copy the code

ShowRemoveConfirmModal () function

// Open the delete confirmation mode box
function showRemoveConfirmModal(a) {
    // 1. Display the modal box
    $("#confirmModal").modal("show");
    // Get role data
 var roleList = getRoleListByRoleIdArray(window.roleIdArray);  // Clear the table data  $("#confirmModalTableBody").empty();  // Populate the confirmModalTableBody data  for (var i = 0; i < roleList.length; i++) {  // 5. Obtain role data  var role = roleList[i];   var id = role.id;  var name = role.name;  var trHTML = "<tr><td>" + (i+1) + "</td><td>" + name + "</td></tr>";  // 6. Perform padding  $("#confirmModalTableBody").append(trHTML);   } } Copy the code

Click the Batch Delete button to bind the response function

Mark the batch delete button

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

Check if itemBox is selected

 // Bind the click response function to the batch delete button
        $("#batchRemoveBtn").click(function () {
            // Get the length of the selected itemBox array
            var length = $(".itemBox:checked").length;
            if (length == 0) {
 layer.msg("Please select the record to delete!!");  return;  }  // To be continued...  }); Copy the code

The confirm message is displayed in the modal box


 // Bind the click response function to the batch delete button
        $("#batchRemoveBtn").click(function () {
            // Get the length of the selected itemBox array
            var length = $(".itemBox:checked").length;
            if (length == 0) {
 layer.msg("Please select the record to delete!!");  return;  }  window.roleIdArray = new Array();  // Iterate over the checkbox  $(".itemBox:checked").each(function () {  // Get the roleID value from the checkbox roleID property  var roleId = $(this).attr("roleid");  // Store to array  window.roleIdArray.push(roleId);  });  // Call the function to open the modal box  showRemoveConfirmModal();   }); Copy the code

Click the OK button in the modal box to perform the deletion

Mark OK according to the

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

Bind the click response function

$("#confirmModalBtn").click(function () {
            // The array is converted to 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("Operation successful!");  // If the deletion succeeds, the paging method is called again  showPage();  }  if (result == "FAILED") {  layer.msg(response.message);  }  // Whether you succeed or fail, you need to close the modal box  $("#confirmModal").modal("hide");  },  "error": function (response) {  if (result == "FAILED") {  layer.msg(response.message);  }  }   });   }); Copy the code

The back-end code

 @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());  }  } Copy the code
public void batchRoleList(List<Integer> roleIds) {
  roleMapper.batchRoleList(roleIds);
 }
Copy the code
<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> Copy the code

Role Maintenance – Added

General steps

  • Bind the Click response function to the Add button

  • Open the modal box

  • Bind the click response function to the Save button

  • Collect text box content

  • Send the request

  • Request processing completes to close the modal box, re-page, and clean up the form

Bind the click response function to the new button

Mark new button

 <button type="button" class="btn btn-primary" id="addBtn"
                            style="float: right;">
                        <i class="glyphicon glyphicon-plus"> < / I > new </button>
Copy the code

Bind the click response function

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

Prepare the modal box

Prepare the HTML code for the modal box,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>  <h4 class="modal-title">Role to add</h4>  </div>  <div class="modal-body">  <input type="text" id="roleNameInput" class="form-control" placeholder="Please enter role name" />  </div>  <div class="modal-footer">  <button type="button" id="addModalBtn" class="btn btn-default"><i class="glyphicon glyphicon-plus"></i>save</button>  <button type="reset" class="btn btn-primary"><i class="glyphicon glyphicon-refresh"></i>reset</button>  </div>  </form>  </div>  </div> </div>  Copy the code

<%@ include file=”/ web-INF /include-modal-role-add.jsp” %>

Open the modal box

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

Bind the click response function to the Save button

Mark the Save button

  <button id="addModalBtn"  type="button" class="btn btn-success">       <i  class="glyphicon glyphicon-plus"></i>Save the </button>  
Copy the code

Bind the click response function

$("#addModalBtn").click(function () {

            // 1. Collect the contents of the text box
            var roleName = $.trim($("#roleNameInput").val());

 if (roleName == null || roleName == "") {  layer.msg("Please enter a valid role name!");  return;  }   // 2. Send request  $.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("Operation successful!");   // 3. The operation is successful  // Go to the last page  window.pageNum = 999999;  showPage();  }   if (result == "FAILED") {  layer.msg(response.message);  }   // 4. Close the modal box with or without success  $("#addModal").modal("hide");   // 5. Clear the data entered in the text box  $("#roleNameInput").val("");   },  "error": function (response) {  layer.msg(response.message);  }  });   }); Copy the code

Back-end part of the code

 @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());  }  } Copy the code

Common return code

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";
  // Easy to return successful results (without query results)  public static ResultEntity<String> successWithoutData(a) {  return new ResultEntity<String>(SUCCESS, NO_MESSAGE, NO_DATA);  }   // Easy to return successful results (with query results)  public static <E> ResultEntity<E> successWithData(E data) {  return new ResultEntity<E>(SUCCESS, NO_MESSAGE, data);  }   // It is convenient to return the failure result  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(a) {   }   public ResultEntity(String result, String message, T data) {  super(a); this.result = result;  this.message = message;  this.data = data;  }   @Override  public String toString(a) {  return "ResultEntity [result=" + result + ", message=" + message + ", data=" + data + "]";  }   public String getResult(a) {  return result;  }   public void setResult(String result) {  this.result = result;  }   public String getMessage(a) {  return message;  }   public void setMessage(String message) {  this.message = message;  }   public T getData(a) {  return data;  }   public void setData(T data) {  this.data = data;  }  }  Copy the code

Role maintenance – Updates

General steps

Bind the click response function to the edit button

Open the modal box

  • Prepare the modal box
  • Save the roleId to the global variable
  • Gets the roleName of the row where the current button resides
  • Use roleName to echo the form in the modal box
  • Bind the click response function to the Update button
  • Collect text box content
  • Send the request
  • Request processing completes to close the modal box and re-page

Bind the click response function to the edit button

Mark edit button

My – role. Js file

function generateTableBody(pageInfo) {
        / / to omit
        var pencilBtn = " + role.id + "' class='btn btn-primary btn-xs editBtn'>";
      / / to omit
    }
} Copy the code

Prepare the modal box

<%@ 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>  <h4 class="modal-title">Shang Chounet system popup window</h4>  </div>  <div class="modal-body">  <input type="text" id="roleNameInputEdit" class="form-control"  placeholder="Please enter role name" />  </div>  <div class="modal-footer">  <button id="editModalBtn" type="button" class="btn btn-warning">  <i class="glyphicon glyphicon-edit"></i>update </button>  <button type="reset" class="btn btn-primary">  <i class="glyphicon glyphicon-refresh"></i>reset </button> </div>  </form>  </div>  </div> </div>  Copy the code

JSP <%@ include file=”/ web-INF /include-modal-role-edit.jsp” %>

Bind the click response function

 $("#roleTableBody").on("click".".editBtn".function () {

            1. Obtain the roleId of the current button
            window.roleId = $(this).attr("roleId");

 // 2. Obtain the roleName of the row where the current button resides  var roleName = $(this).parents("tr").children("td:eq(2)").text();   // 3. Modify the value of the box in the modal box to display the roleName  $("#roleNameInputEdit").val(roleName);   // 4. Open the modal box  $("#editModal").modal("show");  }); Copy the code

Bind the click response function to the Update button

$("#editModalBtn").click(function () {

            // 1. Obtain the text box value
            var roleName = $.trim($("#roleNameInputEdit").val());

 if (roleName == null || roleName == "") {  layer.msg("Please enter a valid role name!");   return;  }   // 2. Send request  $.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("Operation successful!");   // 3. The operation is successful  showPage();  }   if (result == "FAILED") {  layer.msg(response.message);  }   // 4. Close the modal box with or without success  $("#editModal").modal("hide");   }  });  }); Copy the code

Back-end part of the code

 @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());  }  } Copy the code

Exception mapping is compatible with asynchronous requests

Performance problems

Ajax requests throw exceptions during server-side processing that pass through the exception handler:

@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;  }  } Copy the code

The current exception handling mechanism only returns pages, not jSON-formatted response data for Ajax requests. Therefore, in the process of Ajax request processing, if an exception is thrown and a page with exception information is returned, the Ajax program cannot parse properly, resulting in the page cannot be displayed and work properly, and friendly error messages cannot be presented.

Problem Solution


Asynchronous request characteristics


Tool methods for resolving asynchronous requests

    / * ** Used to determine if a request is asynchronous  * @param request
  * @return
* /
 public static boolean checkAsyncRequest(HttpServletRequest request) {   // 1. Get the corresponding request header  String accept = request.getHeader("Accept");  String xRequested = request.getHeader("X-Requested-With");   // 2. Determine whether the request header data contains the target characteristics  if(  (stringEffective(accept) && accept.contains("application/json"))  ||  (stringEffective(xRequested) && xRequested.contains("XMLHttpRequest"))) { return true;  }   return false;  }   / * ** Determines whether the string is valid * @paramSource Indicates the character string to be verified * @returnTrue indicates valid, false indicates invalid* /  public static boolean stringEffective(String source) {   returnsource ! =null && source.length() > 0;  } Copy the code

Updated exception handler

First introduced:

<dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
</dependency>
Copy the code
@ControllerAdvice
public class CrowdFundingExceptionResolever {
    @ExceptionHandler(value = Exception.class)
    public ModelAndView catchException(  Exception exception,  HttpServletRequest request,  HttpServletResponse response) throws IOException {   // 1. Check the current request  boolean checkAsyncRequestResult = CrowdFundingUtils.checkAsyncRequest(request);   // 2. If the request is asynchronous  if(checkAsyncRequestResult) {   // Use friendly text to display error messages according to the mapping of the exception type in the constant  String exceptionClassName = exception.getClass().getName();   String message = CrowdFundingConstant.EXCEPTION_MESSAGE_MAP.get(exceptionClassName);   if(message == null) {  message = "System unknown error";  }   // 3. Create ResultEntity  ResultEntity<String> resultEntity = ResultEntity.failed(ResultEntity.NO_DATA, message);   // 4. Convert resultEntity to JSON format  Gson gson = new Gson();  String json = gson.toJson(resultEntity);   // 5. Return the JSON as response data to the browser  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;  } }  Copy the code

Constant class

public class CrowdFundingConstant {
 
 public static final Map<String, String> EXCEPTION_MESSAGE_MAP = new HashMap<String, String>();

 static {
 EXCEPTION_MESSAGE_MAP.put("java.lang.ArithmeticException"."An error occurred while the system was performing mathematical operations.");  EXCEPTION_MESSAGE_MAP.put("java.lang.RuntimeException"."An error occurred during system operation.");  EXCEPTION_MESSAGE_MAP.put("com.atguigu.crowd.funding.exception.LoginException"."Error running during login");  } } Copy the code

I am a fu, the author of the public number “A fu chat programming”, “to the back-end technology to keep learning enthusiasts, I will often update JAVA technology articles”, on the way to progress, mutual encouragement!


This article is formatted using MDNICE