An overview of the

Perform paging query, save, update, and delete operations for roles. Use Ajax to initiate requests from the back end and then pass them to the front end

One, role paging query

1. The target

Paging the role data

2. The train of thought

To implement paging steps:

  • 1. Write an SQL query statement using the Mapper interface
  • PageInfo< entity class > XXX (Integer pageNum,Integer pageSize)
  • 3. The serviceImpl implementation class
    • PageHelper.startPage(pageNum,pageSize); // Enable paging
    • Calling the method to start the query returns a List collection
    • PageInfo pageInfo = new PageInfo(roles); // Encapsulate the query result into PageInfo
  • 4. Write the handle

3. Code

3.1 Creating database tables

3.2 Reverse Generation of Resources

3.3 Write query SQL statements, RoleMapper interface

<! --> <select id="selectRoleByKeyword" resultMap="BaseResultMap">
  select id,name from t_role where name like concat("%",#{keyword},"%")
</select>
Copy the code

3.4 RoleService interface and implementation, paging

RoleService interface

// Query Role by keyword, paging, PageNum: total page number * pageSize Number of pages to be displayed on each page ** / pageInfo <Role> getPageInfo(String) keyword,Integer pageNum,Integer pageSize);Copy the code

RoleServiceImpl implementation class

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    /** ** ** ** /
    @Override
    public PageInfo<Role> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {
        // 1. Call PageHelper static to turn on paging
        PageHelper.startPage(pageNum,pageSize);
        // 2. Search by keyword
        List<Role> roles = roleMapper.selectRoleByKeyword(keyword);
        // 3. Encapsulate the query into pageInfo
        PageInfo pageInfo = new PageInfo(roles);
        returnpageInfo; }}Copy the code

3.4 RoleHandle write

/*------------------- paging -------------------*/
/** * jumps to the paging page ** /
@RequestMapping("/role/to/page.html")
public String toPage(a){
    return "role-page";
}
/**
 *  分页功能
 * */
@ResponseBody
@RequestMapping("/role/get/page/info.json")
public ResultEntity<PageInfo<Role>> getPageInfo(
        @RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
        @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize,
        @RequestParam(value = "keyword",defaultValue = "") String keyword
){
    // 1. Call Service to get paging data
    PageInfo<Role> pageInfo = roleService.getPageInfo(keyword, pageNum, pageSize);
    // 2. Encapsulate it into a ResultEntity object and return it. If the above operation fails, it will be handed to the exception mapping.
    return ResultEntity.successWithData(pageInfo);
}
Copy the code

3.5 write a role – page. The JSP

3.6 Modifying a Role Maintenance Link – Jump

3.7 Initializing Data to prepare for paging

$(function (){
    // 1. Initialize in preparation for paging operations
    window.pageNum=1;
    window.pageSize=5;
    window.keyword="";
    // 2. Call the paging function to display the paging result
    generatePage();
    }
Copy the code

3.8 Creating external JS files

// 1. Perform paging to generate page effects. Any time this function is called, the page is reloaded
function generatePage(){
    // 1.1. Get pageInfo data
      getPageInfoRemote();
}

// 2. Remotely access the pageInfo data from the server
function getPageInfoRemote(){
    $.ajax({
        url:"role/get/page/info.json".type:"post".data: {"pageNum":window.pageNum,
            "pageSize":window.pageSize,
            "keyword":window.keyword
        },
        dataType:"json".success:function (resp){
            var pageInfo = resp.data;
            //console.log(pageInfo);
            // Fill the pageInfo information into the table
            fillTableBody(pageInfo);
        },
        error:function (resp){}}); }// 3. Display paginated body data
function fillTableBody(pageInfo){
    // 3.1 Clear old tbody data
    $("#rolePageBody").empty();
    $("#Pagination").empty();
    // 3.2 Check whether pageInfo is valid
    if (pageInfo==null||pageInfo == undefined || pageInfo.list == null || pageInfo.list.length ==0){
        $("#rolePageBody").append(" Sorry, the data you searched for was not found 
      ");
        return ;
    }
    for(var i = 0; i < pageInfo.list.length; i++) {
        var role = pageInfo.list[i];
        var roleId = role.id;
        var roleName = role.name;
        var numberTd = "<td>"+(i+1) +"</td>";
        var checkboxTd = "<td><input type='checkbox'></td>";
        var roleNameTd = "<td>"+roleName+"</td>";
        var checkBtn = "<button type='button' class='btn btn-success btn-xs'><i class=' glyphicon glyphicon-check'></i></button>";
        // 3.3 Pass the roleId value to the button click response function via the BUTTON id attribute
        var pencilBtn = "<button id='"+roleId+"' type='button' class='btn btn-primary btn-xs pencilBtn '><i class=' glyphicon glyphicon-pencil '></i></button>";
        var removeBtn = "<button type='button' class='btn btn-danger btn-xs'><i class=' glyphicon glyphicon-remove'></i></button>";
        var buttonTd = "<td>"+checkBtn+""+pencilBtn+""+removeBtn+"</td>";
        var tr = "<tr>"+numberTd+checkboxTd+roleNameTd+buttonTd+"</tr>";
        $("#rolePageBody").append(tr);
    }
        3.4 Generate a paging navigation bar
    generateNavigator(pageInfo);
}

// 4. Generate a paging page number navigation bar
function generateNavigator(pageInfo){
    // 4.1. Get total records
    var totalRecord = pageInfo.total;
    Declare a JSON object to store Pagination properties
    var properties={
        num_edge_entries: 3.// Number of edge pages
        num_display_entries: 5.// Number of main pages
        callback: paginationCallBack,                          // Specifies the function that jumps to the page when the user clicks the page turn button
        items_per_page: pageInfo.pageSize,                     // The number of columns per page
        current_page: pageInfo.pageNum-1.//pageNum starts at 1. Pagination starts at 0
        prev_text: "Previous page".// The text displayed on the previous button
        next_text: "Next page"                                     // The text displayed on the next page button
    }
    4.3 Generate a page number navigation bar
    $("#Pagination").pagination(totalRecord,properties);
}

// 6. Page-turning callback
function paginationCallBack(pageIndex,jQuery){
    // 6.1 Modifying the pageNum property of the Window object
    window.pageNum=pageIndex+1;
    // 6.2 Calling the paging function
    generatePage();
    // 6.3 Cancel the default behavior of page number hyperlinks
    return false;
}
Copy the code

Introduce external JavaScript file role-.js in role-page.jsp, Pagination environment

2. Role query operation

1. The target

Connect the “query” form on the page to the function that performs paging that has been wrapped up

2. The train of thought

3. Code

3.1 Adding a Query ID

3.2 modify the role – page

3. Role saving operation

1. The target

Perform the save of the new role by entering the role name in the modal box that opens

2. The train of thought

3. Code

3.1 Introduction of modal boxes

<%@ page contentType="text/html; charset=UTF-8" language="java"% > <! DOCTYPE html> <div id="myModal" 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> <h4class="modal-title"> New character </h4> </div> <divclass="modal-body">
                <form  class="form-signin" role="form">
                    <div class="form-group has-success has-feedback">
                        <input type="text" name="roleName" class="form-control"  placeholder="Please enter role name" autofocus>
                        <span class="glyphicon glyphicon-user form-control-feedback"></span>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" id="saveRoleBtn" class="btn btn-primary"</button> </div> </div>Copy the code

3.2 Introduce the above file in role-page.jsp

3.3 role – page code

// 4. Add a single machine response function to the save button in the new modal box
$("#saveRoleBtn").click(function (){
    /** * There are two ways to get a character name:  * var roleName = $.trim($("#addModal [name=roleName]").val()) * var roleName = $('input[name="roleName"]').val(); * * /
    ① Obtain the role name entered by the user in the text box
    // #addModal means to find the entire modal box
    // Whitespace indicates continuing search in descendant elements
    // [name=roleName] matches elements whose name attribute is roleName
    //var roleName = $.trim($("#addModal [name=roleName]").val())
    var roleName = $('input[name="roleName"]').val();
    $.ajax({
        url:"role/save.json",
        type:"post",
        data:{"name":roleName},
        dataType:"json",
        success:function (resp){
            var result = resp.result;
            if (result=="SUCCESS"){
                layer.msg("Operation successful!");
            }
            if(result=="FAILED"){
                layer.msg("Operation failed!"+resp.message);
            }
        },
        error:function (resp){
            layer.msg(resp.status+""+resp.statusText); }});//alert(roleName);
    // Close the modal box
    $('#myModal').modal('hide');
    // Clean up the modal box
    $('input[name="roleName"]').val("");
    /*// reload the updated page data window.keyword=roleName; generatePage(); * /
});
Copy the code

3.5 Back-end code

1.Controller

/**
 *   新增角色
 * */
@ResponseBody
@RequestMapping("/role/save.json")
public ResultEntity<String> addRole(@RequestParam("name") String roleName){

    roleService.save(new Role(null,roleName));
    return ResultEntity.successWithoutData();
}
Copy the code

2.Service

void save(Role role);
Copy the code

3.ServiceImpl

/**
 *   新增角色
 * */
@Override
public void save(Role role) {
    roleMapper.insert(role);
}
Copy the code

4. Role update operation

1. The target

Update the role information, click the modify button, pop up the modal box, save the update.

2. The train of thought

3. Code

3.1 Create a model-role-edit. JSP and add the modal box

<%@ page contentType="text/html; charset=UTF-8" language="java"% > <! DOCTYPE html> <div id="editModal" 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> <h4class="modal-title"> Update role </h4> </div> <divclass="modal-body">
                <form  class="form-signin" role="form">
                    <div class="form-group has-success has-feedback">
                        <input type="text" name="roleName" class="form-control"  placeholder="Please enter role name" autofocus>
                        <span class="glyphicon glyphicon-user form-control-feedback"></span>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" id="updateRoleBtn" class="btn btn-primary"</button> </div> </div>Copy the code

3.2 Introduce modal boxes in role-page.jsp

3.3 Opening the Modal Box (Command Output)

3.3.1 modified role. Js

var pencilBtn = "<button id='"+roleId+"' type='button' class='btn btn-primary btn-xs pencilBtn '><i class=' glyphicon glyphicon-pencil '></i></button>";
Copy the code

3.3.2 Bind the pencil to the click response function, and the modal box pops up

Modify the role – page. The JSP

// 5. Bind the "Pencil" button to the click event, and the modal box is displayed
The first argument to the on() function is the event type. The second argument to the on() function is the selector to find the element to which the event is actually bound. The third argument to the on() function is the time response function ** /
$("#rolePageBody").on("click".".pencilBtn",function (){

    $('#editModal').modal('show');
    Get the name of the current row in the table
    var roleName = $(this).parent().prev().text();
    // Pass the name to the text box in the modal box
    $("#editModal [name=roleName]").val(roleName);

    // Get the id of the current role
    Var pencilBtn = "
    // To get the roleId for the updated button, place it in the global variable
    window.roleId=this.id;
})
Copy the code

3.3.3 Bind the click event to the update button in the modal box

        // 6. Bind the update button to the click event
        $("#updateRoleBtn").click(function (){

            // Get the name in the updated text box
            var roleName =  $("#editModal [name=roleName]").val();
           $.ajax({
               url:"role/update.json",
               type:"post",
               data:{
                   "id":window.roleId,
                   "name":roleName
               },
               dataType: "json",
               success:function (resp){
                   var result = resp.result;

                   if (result=="SUCCESS"){
                       layer.msg("Operation successful!");
                   }
                   if(result=="FAILED"){
                       layer.msg("Operation failed!"+resp.message);
                   }
               },
               error:function (resp){
                   layer.msg(resp.status+""+resp.statusText); }}); $('#editModal').modal('hide');
            // Reload refreshed page data
            generatePage();
        });
    });
</script>
Copy the code

We do the back-end

RoleController

/** * Update the role ** /

@ResponseBody
@RequestMapping("/role/update.json")
public ResultEntity<String> update(@RequestParam("id") Integer id,
                                   @RequestParam("name") String roleName){
    roleService.updateRole(new Role(id,roleName));
    return ResultEntity.successWithoutData();
}
Copy the code

RoleService

void updateRole(Role role);
Copy the code

ROleServiceImpl

/** * Update the role ** /
@Override
public void updateRole(Role role) {
    roleMapper.updateByPrimaryKey(role);
}
Copy the code

Delete the role

1. The target

The front-end “single delete” and the back-end “batch delete” are merged into the same set. The merging basis is that the id of a single delete is also placed in the array, and the back-end is completely deleted according to the array of IDS

2. The train of thought

3. Code

3.0 front end: Write modal boxes

<%@ page contentType="text/html; charset=UTF-8" language="java"% > <! DOCTYPE html><div id="removeModal" 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">Delete the role</h4>
            </div>
            <div class="modal-body" style="text-align: center">
                <h4 >Confirm whether you want to delete the following roles</h4>
                <div id="roleNameDiv" >

                </div>
            </div>
            <div class="modal-footer">
                <button type="button" id="removeRoleBtn" class="btn btn-primary">Confirm the deletion</button>
            </div>
        </div>
    </div>
</div>
Copy the code

3.1 Front end: Declare functions to open the modal box

/ * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- delete operation modal box -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * / * * * declare special function identified modal dialog * * /
function showConfirmModal(roleArray){
    1. Open the modal box
    $('#removeModal').modal('show');
    
    // 2. Create a global id array
    window.roleIdArray=[];
    
    // 3. Clear old data
    $("#roleNameDiv").empty();
    
    // 4. Iterate through the roleArray array
    for (var i = 0; i<roleArray.length; i++){var role = roleArray[i];
        var roleName = role.roleName;
        $("#roleNameDiv").append(roleName+"</br>");
        var roleId = role.roleId;
        // 5. Store the id in the array
        window.roleIdArray.push(roleId); }}Copy the code

3.2 Front end: Add a response function to the confirm button delete button in the modal box

role-page.jsp

// 7. Click the Confirm delete button in the modal box to delete
$("#removeRoleBtn").click(function (){
    // Get the roleIdArray from the global variable range and convert the JSON array to a JSON string
    var requestBody = JSON.stringify(window.roleIdArray);
    $.ajax({
        url:"role/remove/byId/array.json",
        type:"post",
        data:requestBody,
        contentType:"application/json; charset=UTF-8",
        dataType:"json",
        success:function (resp){
            var result = resp.result;
            if (result=="SUCCESS"){
                generatePage();
                layer.msg("Operation successful!");
            }
            if(result=="FAILED"){
                layer.msg("Operation failed!"+resp.message);
            }
        },
        error:function (resp){
            layer.msg(resp.status+""+resp.statusText); }});// Close the modal box
    $('#removeModal').modal('hide');

    // If you select all, click the delete button to delete all
    if ($("#summaryBox").is(":checked")){
        $("#summaryBox").prop("checked".false); }});Copy the code

3.3 Front end: Bind the click response function to a single delete button

role.js

var removeBtn = "<button id='"+roleId+"' type='button' class='btn btn-danger btn-xs removeBtn'><i class=' glyphicon glyphicon-remove'></i></button>";
Copy the code

role-page.jsp

// 8. Bind the single delete button to the click function, similar to the pencil button above
$("#rolePageBody").on("click".".removeBtn".function (){

    Get the name of the current row in the table
    var roleName = $(this).parent().prev().text();

    // Create an array of role objects
    var roleArray=[{
        roleName:roleName,
        roleId:this.id
    }];
    // Call the function to open the modal box
    showConfirmModal(roleArray);
    // Get the id of the current role
    Var pencilBtn = "
    // To get the roleId for the updated button, place it in the global variable
    //window.roleId=this.id;
});
Copy the code

3.4 Front-end: Bind the total checkBox to the click function

$("#summaryBox").click(function (){
    // 1. Obtain the status of the current checkbox
    var currentStatus = this.checked;

    // 2. Use the current multi-check box status to set other multi-check boxes
    $(".itemBox").prop("checked",currentStatus);
});
Copy the code

3.5 Front End: Reverse operations for All and None

$("#rolePageBody").on("click".".itemBox".function (){
    // Get the number of currently selected ItemBoxes
    var checkedBoxCount = $(".itemBox:checked").length;
    // Get the total number of itemBoxes
    var totalBoxCount = $(".itemBox").length;
    // Use the comparison result to set the total checkbox
    $("#summaryBox").prop("checked",checkedBoxCount==totalBoxCount);
});
Copy the code

3.6 Front end: Bind click function response function to batch delete button

$("#deleteRoleModel").click(function (){
    // Create an array to store the acquired role objects
    var roleArray= [];
    // Iterate over the currently selected multiple boxes
    $(".itemBox:checked").each(function (){
        // Use this to refer to the checkbox generated by the current iteration
        var roleId = this.id;
        // Get the role name by dom manipulation
        var roleName = $(this).parent().next().text();
        roleArray.push({
            "roleId":roleId,
            "roleName":roleName
        });
    });
    // Check whether the length of roleArray is 0
    if(roleArray.length==0){
        layer.msg("Please select at least one to delete!");
        return ;
    }
    // Call a special function to open the modal box
    showConfirmModal(roleArray);
});
Copy the code

3.7 Back end: RoleMapper interface

// Reverse generated code
int deleteByExample(RoleExample example)
Copy the code

3.8 Back end: Rolemapper.xml

<delete id="deleteByExample" parameterType="com.hejinjie.crowd.entity.RoleExample" >
  delete from t_role
  <if test="_parameter ! = null" >
    <include refid="Example_Where_Clause" />
  </if>
</delete>
Copy the code

3.9 Back end: RoleService. Java interface

Parameter: List collection

void remove (List<Integer> roleList);
Copy the code

3.10 Backend: RoleServiceImpl

With QBC, there is no need to write SQL to dynamically concatenate

/** * use QBC to delete objects ** /
@Override
public void remove(List<Integer> roleList) {
    // Use QBC to query
    1. Create the example object
    RoleExample example = new RoleExample();
    // 2. Create Criteria with example. Criteria is used to store parameters
    Criteria criteria = example.createCriteria();
    Where id in (5,8,12);
    criteria.andIdIn(roleList);
    // 4. Pass example as an argument to the query method
    roleMapper.deleteByExample(example);
}
Copy the code

3.11 Backend: RoleController

/** * Delete operation ** /
@ResponseBody
@RequestMapping("/role/remove/byId/array.json")
public ResultEntity<Integer> removeRoleById(@RequestBody List<Integer> roleIdList){

    roleService.remove(roleIdList);
    return ResultEntity.successWithoutData();
}
Copy the code