Since the videos in Silicon Valley are made by Eclipse software, some of which are different from IDEA, I'm here to share with you the differences between IDEA and Eclipse's operation, the source code involved in the operation (slightly different from the source code of the video), and the various problems you may encounter. These sources are tested here, for reference only!
1 Create database tables
Created in SQLLyog:
CREATE TABLE `t_role` ( id INT NOT NULL AUTO_INCREMENT, NAME CHAR(100), PRIMARY KEY (id) );
2 mybatis reverse engineering
Modify reverse\src\main\resources\generatorConfig.xml
<!-- Database Table Name and Our entity Mapping assignment for class --> <table tableName="t_admin" domainObjectName="Admin" /> <table tableName="t_role" domainObjectName="Role" />
Find mybatis-generator:generate in the maven project on the right side of IDEA and click Run to generate the file:
Modify reversesrc\main\java\comatguigu\crowdentity\Role. Java
public Role() { } public Role(Integer id, String name) { this.id = id; this.name = name; } @Override public String toString() { return "Role{" + "id=" + id + ", name='" + name + '\'' + '}'; }
Will Role.java and RoleExample. Put Java in entity\src\main\java\comatguigu\crowd\entity
RoleMapper. Put Java in componentsrc\main\java\comatguigu\crowdmapper
RoleMapper. Put XML in webui\src\main\resources\mybatis\mapper
3 rear part
3.1 RoleMapper
Modify componentsrc\main\java\comatguigucrowdmapper\RoleMapper. Java
List<Role> selectRoleByKeyword(String keyword);
Modify webui\src\mainresources\mybatismapper\RoleMapper. XML
<select id="selectRoleByKeyword" resultMap="BaseResultMap"> select id, name from t_role where name like concat("%",#{keyword},"%") </select>
3.2 RoleService
Create a new RoleService at componentsrc\main\java\comatguigu\crowdservice\api. Java
package com.atguigu.crowd.service.api; import com.atguigu.crowd.entity.Role; import com.github.pagehelper.PageInfo; public interface RoleService { PageInfo<Role> getPageInfo(Integer pageNum, Integer pageSize, String keyword); }
Create a new RoleServiceImpl at componentsrc\main\java\comatguigu\crowdservice\impl. Java
package com.atguigu.crowd.service.impl; import com.atguigu.crowd.entity.Role; import com.atguigu.crowd.mapper.RoleMapper; import com.atguigu.crowd.service.api.RoleService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class RoleServiceImpl implements RoleService { @Autowired private RoleMapper roleMapper; @Override public PageInfo<Role> getPageInfo(Integer pageNum, Integer pageSize, String keyword) { // 1. Turn on paging PageHelper.startPage(pageNum,pageSize); // 2. Execute the query List<Role> roleList = roleMapper.selectRoleByKeyword(keyword); // 3. Encapsulate as PageInfo Object Return return new PageInfo<>(roleList); } }
Create a new RoleHandler in componentsrc\main\java\comatguigu\crowdmvc\handler. Java
package com.atguigu.crowd.mvc.handler; import com.atguigu.crowd.entity.Role; import com.atguigu.crowd.service.api.RoleService; import com.atguigu.crowd.util.ResultEntity; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class RoleHandler { @Autowired private RoleService roleService; @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) { // Call service to get paging data PageInfo<Role> pageInfo = roleService.getPageInfo(pageNum,pageSize,keyword); // Return encapsulated in a ResultEntity object (if the above operation throws an exception, handled by the exception mapping mechanism) return ResultEntity.successWithData(pageInfo); } }
3.3 Test
Open directly: http://localhost:8080/atcrowdfunding02_admin_webui_war_exploded/role/get/page/info.json , add some data in advance, it will show
4 Front Section
4.1 New Page
Modify webui\src\mainresources\spring-web-mvc. XML
<mvc:view-controller path="/role/to/page.html" view-name="role-page"/>
Create a new role-page in webui\src\main\webapp\WEB-INF. JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html lang="zh-CN"> <%@include file="include-head.jsp" %> <body> <%@include file="include-nav.jsp" %> <div class="container-fluid"> <div class="row"> <%@include file="include-sidebar.jsp" %> <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"><i class="glyphicon glyphicon-th"></i> Data List</h3> </div> <div class="panel-body"> <form class="form-inline" role="form" style="float:left;"> <div class="form-group has-feedback"> <div class="input-group"> <div class="input-group-addon">query criteria</div> <input class="form-control has-success" type="text" placeholder="Please Enter query criteria"> </div> </div> <button type="button" class="btn btn-warning"><i class="glyphicon glyphicon-search"></i> query</button> </form> <button type="button" class="btn btn-danger" style="float:right;margin-left:10px;"><i class=" glyphicon glyphicon-remove"></i> delete</button> <button type="button" class="btn btn-primary" style="float:right;" οnclick="window.location.href='form.html'"><i class="glyphicon glyphicon-plus"></i> Newly added</button> <br> <hr style="clear:both;"> <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr> <th width="30">#</th> <th width="30"><input type="checkbox"></th> <th>Name</th> <th width="100">operation</th> </tr> </thead> <tbody> <tr> <td>1</td> <td><input type="checkbox"></td> <td>PM - project manager</td> <td> <button type="button" class="btn btn-success btn-xs"><i class=" glyphicon glyphicon-check"></i></button> <button type="button" class="btn btn-primary btn-xs"><i class=" glyphicon glyphicon-pencil"></i></button> <button type="button" class="btn btn-danger btn-xs"><i class=" glyphicon glyphicon-remove"></i></button> </td> </tr> </tbody> <tfoot> <tr> <td colspan="6" align="center"> <ul class="pagination"> <li class="disabled"><a href="#">Previous page</a></li> <li class="active"><a href="#">1 <span class="sr-only">(current)</span></a></li> <li><a href="#">2</a></li> <li><a href="#">3</a></li> <li><a href="#">4</a></li> <li><a href="#">5</a></li> <li><a href="#">Next page</a></li> </ul> </td> </tr> </tfoot> </table> </div> </div> </div> </div> </div> </div> </body> </html>
Modify webui\src\main\webapp\WEB-INF\include-sidebar.jsp
<a href="role/to/page.html"><i class="glyphicon glyphicon-king"></i> Role Maintenance</a></li>
4.2 New Paging
Modify webui\src\main\webapp\WEB-INF\role-page.jsp
<%@include file="include-head.jsp" %> <link rel="stylesheet" href="css/pagination.css"> <script type="text/javascript" src="jquery/jquery.pagination.js"></script> <script type="text/javascript" src="js/my-role.js"></script> <script type="text/javascript"> $(function (){ // 1. Preparing initialization data for paging operations window.pageNum = 1; window.pageSize = 5; window.keyword = ""; // 2. Call paging function to achieve paging effect generatePage(); }); </script>
<tbody id="rolePageBody"></tbody> <tfoot> <tr> <td colspan="6" align="center"> <div id="Pagination" class="pagination"><!--Paging is shown here--></div> </td> </tr> </tfoot>
Create a new my-role in webui\src\main\webapp\crowd. JS
// Perform paging, generate page effects, and reload pages whenever this function is called function generatePage() { // 1. Get paging data var pageInfo = getPageInfoRemote(); // 2. Fill in the table fillTableBody(pageInfo); } // Remote Access Server-Side Programs Get pageInfo Data function getPageInfoRemote() { console.log("pageNum="+window.pageNum); // Invoke $. The ajax() function sends the request and accepts the $. Return value of ajax() function var ajaxResult = $.ajax({ url: "role/get/page/info.json", type: "post", data: { "pageNum": window.pageNum, "pageSize": window.pageSize, "keyword": window.keyword }, async: false, dataType: "json" }); console.log(ajaxResult); // Determine if the current response status code is 200 var statusCode = ajaxResult.status; // If the current response status code is not 200, an error or other unexpected event occurs, a prompt message is displayed to stop the execution of the current function if (statusCode != 200) { layer.msg("Failed! Response Status Code="+statusCode+" Description Information="+ajaxResult.statusText); return null; } // If the response code is 200, the request is processed successfully and pageInfo is obtained var resultEntity = ajaxResult.responseJSON; // Get the result property from the resultEntity property var result = resultEntity.result; // Determine success of result if (result == "FAILED"){ layer.msg(resultEntity.message); return null; } // Acquire pageInfo after confirming result is successful var pageInfo = resultEntity.data; // Return pageInfo return pageInfo; } // Fill in the table function fillTableBody(pageInfo) { // Clear old content from tbody $("#rolePageBody").empty(); // This is empty to keep the page number navigation bar from showing when there are no search results $("#Pagination").empty(); // Determine whether pageInfo is valid if (pageInfo == null || pageInfo.list == null || pageInfo.list.length === 0){ $("#RolePageBody ").append ("<tr><td colspan='4'align='center'>Sorry! No data was queried for your search </td></tr>"); return; } // Populate tBody with page Info's list attribute 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>"; var pencilBtn = "<button type=\"button\" class=\"btn btn-primary btn-xs\"><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); } // Generate Paging Navigation Bar generateNavigator(pageInfo); } // Generate Paging Number Navigation Bar function generateNavigator(pageInfo) { // Get Total Records var totalRecord = pageInfo.total; // Declare related properties var properties = { "num_edge_entries": 3, "num_display_entries": 5, "callback": paginationCallBack, "items_per_page":pageInfo.pageSize, "current_page": pageInfo.pageNum - 1, "prev_text": "Previous page", "next_text": "next page" }; // Calling the pagination() function $("#Pagination").pagination(totalRecord, properties); } // Callback function when page flipping function paginationCallBack(pageIndex,jQuery) { // Modify pageNum property of window object window.pageNum = pageIndex + 1; // Call Paging Function generatePage(); // Cancel the default behavior of page number hyperlinks return false; }
Test:
Note: If the "previous page" and "next page" appear garbled, you need to modify the Tomcat configuration and clear the browser cache.
5 Role Information CRUD
5.1 Query role information
Modify webui\src\main\webapp\WEB-INF\role-page.jsp
The query button function gives:
<form class="form-inline" role="form" style="float:left;"> <div class="form-group has-feedback"> <div class="input-group"> <div class="input-group-addon">query criteria</div> <input id="keywordInput" class="form-control has-success" type="text" placeholder="Please Enter query criteria"> </div> </div> <button id="searchBtn" type="button" class="btn btn-warning"><i class="glyphicon glyphicon-search"></i> query</button> </form>
Response function:
<script type="text/javascript"> $(function (){ // 1. Preparing initialization data for paging operations window.pageNum = 1; window.pageSize = 5; window.keyword = ""; // 2. Call paging function to achieve paging effect generatePage(); // 3. Bind query buttons to click response functions $("#searchBtn").click(function (){ // Get keyword data to assign to corresponding global variables window.keyword = $("#keywordInput").val(); // Call Paging Function to Refresh Page generatePage(); }); }); </script>
Test:
5.2 New Role Information
Add modal-role-add to webui\src\main\webapp\WEB-INF. JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <div id="addModal" 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">Prepare network system pop-up window</h4> </div> <div class="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 a role name" autofocus> <span class="glyphicon glyphicon-user form-control-feedback"></span> </div> </form> </div> <div class="modal-footer"> <button id="saveRoleBtn" type="button" class="btn btn-primary">Preservation</button> </div> </div> </div> </div>
Modify webui\src\main\webapp\WEB-INF\role-page.jsp
The query button function gives:
<button type="button" id="showAddModalBtn" class="btn btn-primary" style="float:right;" ><i class="glyphicon glyphicon-plus"></i> Newly added</button>
Response function:
// 4. Click the Add button to open the modal box $("#showAddModalBtn").click(function (){ $("#addModal").modal("show"); }); // 5. Bind the Save button in the new modal box to the Click Response Function $("#saveRoleBtn").click(function (){ // Gets the role name that the user enters in the text box. // #addModal means the entire modal box is found // Spaces indicate that a search continues in a descendant element // [name=roleName] Indicates an element whose matching name attribute equals roleName var roleName = $.trim($("#addModal [name=roleName]").val()); // Send an ajax request $.ajax({ url: "role/save.json", type: "post", data: { roleName: roleName }, dataType: "json", success: function (response){ let result = response.result; if (result === "SUCCESS") { layer.msg("Operation successful!"); // Position page number to last page window.pageNum = 99999999; // Reload Paging Data generatePage(); } if (result === "FAILED") { layer.msg("Operation failed!"+response.message); } }, error: function (response) { layer.msg(response.status+""+response.statusText); } }); // Close the modal box $("#addModal").modal("hide"); // Clean up the modal box $("#addModal [name=roleName]").val(""); });
Modal-role-add is introduced at the end. Jsp:
<%@include file="/WEB-INF/modal-role-add.jsp"%>
Modify componentsrc\main\java\comatguigu\crowdmvc\handlerRoleHandler. Java
@ResponseBody @RequestMapping("/role/save.json") public ResultEntity<String> saveRole(Role role) { roleService.saveRole(role); return ResultEntity.successWithoutData(); }
A new saverole() method and implementation class are added:
Modify componentsrc\main\java\comatguigu\crowdservice\impl\AdminServiceImpl. Java
@Override public void saveRole(Role role) { roleMapper.insert(role); }
Test:
5.3 Update role information
Add modal-role-edit to webui\src\mainwebapp\WEB-INF. JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <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">×</span></button> <h4 class="modal-title">System pop-up window</h4> </div> <div class="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 a role name" autofocus> <span class="glyphicon glyphicon-user form-control-feedback"></span> </div> </form> </div> <div class="modal-footer"> <button id="updateRoleBtn" type="button" class="btn btn-success">To update</button> </div> </div> </div> </div>
Modify webui\src\main\webapp\WEB-INF\role-page.jsp
Response function:
// 6. Bind the Click Response Function to the Pencil button on the page to open the modal box // The traditional event binding method only works on the first page, but does not work after page flipping // $(".pencilBtn").click(function(){ // alert("aaaa..."); // }); // Use the on() function of the jQuery object to solve the above problem // First find the static elements attached to all dynamically generated elements // (2) The first parameter of the on() function is the event type // (3) The second argument to the on() function is to find the selector for the element that actually binds the event // The third parameter of the on() function is the event response function $("#rolePageBody").on("click",".pencilBtn", function (){ // Open the modal box $("#editModal").modal("show"); // Gets the role name in the current row in the table var roleName = $(this).parent().prev().text(); // Get the current role id window.roleId = this.id; // Set the text box in the modal box with the value of roleName $("#editModal [name=roleName]").val(roleName); }); // 7. Bind a single machine response function to the update button in the update mode box $("#updateRoleBtn").click(function (){ // (1) Get a new role name from the text box var roleName = $("#editModal [name=roleName]").val(); // (2) Send ajax requests for updates $.ajax({ url: "role/update.html", type: "post", data: { id: window.roleId, name: roleName }, dataType: "json", success: function (response){ let result = response.result; if (result === "SUCCESS") { layer.msg("Update successful!"); // Reload Paging Data generatePage(); } if (result === "FAILED") { layer.msg("Operation failed!"+response.message); } }, error: function (response) { layer.msg(response.status+""+response.statusText); } }); // Close the modal box $("#editModal").modal("hide"); });
Modal-role-edit is introduced at the end. Jsp:
<%@include file="/WEB-INF/modal-role-edit.jsp"%>
Modify the pencil button: webui\src\main\webapp\crowd\my-role.js
// The role id value is passed to the button button's click response function through the button tag's id attribute (other attributes can actually be used), which is used in the click response function. id var pencilBtn = "<button id='" + roleId + "'type='button' class='btn btn-primary btn-xs pencilBtn'><i class='glyphicon glyphicon-pencil'></i></button>";
Modify componentsrc\main\java\comatguigu\crowdmvc\handlerRoleHandler. Java
@ResponseBody @RequestMapping("/role/update.json") public ResultEntity<String> updateRole(Role role) { roleService.updateRole(role); return ResultEntity.successWithoutData(); }
The updateRole() method and implementation class are added:
Modify componentsrc\main\java\comatguigu\crowdservice\impl\AdminServiceImpl. Java
@Override public void updateRole(Role role) { roleMapper.updateByPrimaryKey(role); }
Test:
5.4 Delete role information
Modify componentsrc\main\java\comatguigu\crowdmvc\handlerRoleHandler. Java
@ResponseBody @RequestMapping("/role/remove/by/role/id/array.json") public ResultEntity<String> removeByRoleIdArray(@RequestBody List<Integer> roleIdList) { roleService.removeRole(roleIdList); return ResultEntity.successWithoutData(); }
A new removeRole() method and implementation class are added:
Modify componentsrc\main\java\comatguigu\crowdservice\impl\AdminServiceImpl. Java
@Override public void removeRole(List<Integer> roleIdLList) { RoleExample example = new RoleExample(); RoleExample.Criteria criteria = example.createCriteria(); criteria.andIdIn(roleIdLList); roleMapper.deleteByExample(example); }
Add modal-role-confirm to webui\src\main\webapp\WEB-INF. JSP
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <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">System pop-up window</h4> </div> <div class="modal-body"> <h4>Please confirm that you want to delete the following roles</h4> <div id="roleNameDiv" style="text-align: center;"></div> </div> <div class="modal-footer"> <button id="removeRoleBtn" type="button" class="btn btn-primary">confirm deletion</button> </div> </div> </div> </div>
Modify webui\src\main\webapp\crowd\my-role.js
Open the modal box:
// Declare special functions to display confirmation mode boxes function showConfirmModal(roleArray) { // Open the modal box $("#confirmModal").modal("show"); // Clean up old data $("#roleNameDiv").empty(); // Create an array at the global variable scope to hold the role id window.roleIdArray = []; // Traversing 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; // Call the push() method of the array object to save the new element window.roleIdArray.push(roleId); } }
5.4.1 Single Delete
Modify the Delete button: webui\src\main\webapp\crowd\my-role.js
var removeBtn = "<button id='" + roleId + "' type=\"button\" class=\"btn btn-danger btn-xs removeBtn\"><i class=\" glyphicon glyphicon-remove\"></i></button>";
Modify webui\src\main\webapp\WEB-INF\role-page.jsp
// 8. Click the Confirm Delete button in the Confirm modal box to perform the deletion $("#removeRoleBtn").click(function (){ // Get roleIdArray from global variable scope, convert to JSON string var requestBody = JSON.stringify(window.roleIdArray); $.ajax({ url: "role/remove/by/role/id/array.json", type: "post", data: requestBody, contentType: "application/json;charset=utf-8", dataType: "json", success: function (response){ var result = response.result; if (result === "SUCCESS") { layer.msg("Operation successful!"); // Reload Paging Data generatePage(); } if (result === "FAILED") { layer.msg("Operation failed!"+response.message); } }, error: function (response) { layer.msg(response.status+""+response.statusText); } }); // Close the modal box $("#confirmModal").modal("hide"); }); // 9. Single Delete $("#rolePageBody").on("click", ".removeBtn", function (){ // Get the role name from the current button var roleName = $(this).parent().prev().text(); // Create role object into array var roleArray = [{ roleId: this.id, roleName: roleName }]; // Call function to open modal box showConfirmModal(roleArray); });
Modal-role-confirm is introduced at the end. Jsp:
include file="/WEB-INF/modal-role-confirm.jsp"%>
5.4.2 Select All Not Select
Modify checkbox:
webui\src\main\webapp\WEB-INF\role-page.jsp
<tr> <th width="30">#</th> <th width="30"><input id="summaryBox" type="checkbox"></th> <th>Name</th> <th width="100">operation</th> </tr>
webui\src\main\webapp\crowd\my-role.js
var checkboxTd = "<td><input class='itemBox' id='" + roleId + "' type='checkbox'></td>";
Modify webui\src\main\webapp\WEB-INF\role-page.jsp
// 10. Click Response Function for Total checkbox Binding $("#summaryBox").click(function (){ // (1) Get the current state of the multicheck box itself var currentStatus = this.checked; // (2) Set other multiple check boxes with the current state of multiple check boxes $(".itemBox").prop("checked", currentStatus); }); // 11. All-Select, None-Select Reverse Operations $("#rolePageBody").on("click",".itemBox",function (){ // Gets the currently selected. Number of itemBox es var checkedBoxCount = $(".itemBox:checked").length; // Get all. Number of itemBox es var totalBoxCount = $(".itemBox").length; // Set the total checkbox using the results of the comparison between the two $("#summaryBox").prop("checked", checkedBoxCount === totalBoxCount); });
Test:
5.4.3 Bulk Delete
Modify webui\src\main\webapp\WEB-INF\role-page.jsp
// 12. Bind Button Buttons for Bulk Deletion Click Response Function $("#batchRemoveBtn").click(function (){ // Create an array object to hold the role object you get later var roleArray = []; // Traverse the currently selected multiple check box $(".itemBox:checked").each(function (){ // Use this to reference the currently traversed multiple checkboxes var roleId = this.id; // Getting role names through DOM operations var roleName = $(this).parent().next().text(); roleArray.push({ roleId: roleId, roleName: roleName }); }); // Check if 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 confirmation mode box showConfirmModal(roleArray); });
The Delete button function gives:
<button type="button" id="batchRemoveBtn" class="btn btn-danger" style="float:right;margin-left:10px;"><i class=" glyphicon glyphicon-remove"></i> delete</button>
Test: