20、尚硅谷_SSM高級整合_新增_建立員工新增的模態框.avijavascript
一、接下來當咱們點擊增長按鈕的時候會彈出一個員工信息的對話框css
知識點1:當點擊新增的時候會彈出一個bootstrap的一個模態對話框html
<!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <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" id="myModalLabel">Modal title</h4> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div>
知識點2:如何啓動一個模態對話框前端
只需一行 JavaScript 代碼,便可經過元素的 id myModal
調用模態框:java
$('#myModal').modal(options),
myModal對於的是modal對於的id
知識點3:接下面咱們要在modal的boby中添加表單,咱們使用下面的這種bootstap的表單
<form> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password"> </div> <div class="form-group"> <label for="exampleInputFile">File input</label> <input type="file" id="exampleInputFile"> <p class="help-block">Example block-level help text here.</p> </div> <div class="checkbox"> <label> <input type="checkbox"> Check me out </label> </div> <button type="submit" class="btn btn-default">Submit</button> </form>
知識點4:接下來咱們要使用到性別的單選按鈕
整個頁面的index.jsp的代碼以下所示
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>員工列表</title> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <% pageContext.setAttribute("APP_PATH", request.getContextPath()); %> <!-- web路徑: 不以/開始的相對路徑,找資源,以當前資源的路徑爲基準,常常容易出問題。 以/開始的相對路徑,找資源,以服務器的路徑爲標準(http://localhost:3306);須要加上項目名 http://localhost:3306/crud --> <script type="text/javascript" src="${APP_PATH}/static/js/jquery-2.1.1.js"></script> <link href="${APP_PATH }/static/bootstrap-3.3.7/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="${APP_PATH}/static/bootstrap-3.3.7/dist/js/bootstrap.min.js"></script> </head> <body> <!-- 新增員工信息的對話框 --> <div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <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" id="myModalLabel">新增員工</h4> </div> <div class="modal-body"> <!-- 實體類的表單,表單項 的name須要給實體bean對象的一一對應起來,springmvc會幫咱們自動封裝--> <form class="form-horizontal"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">姓名</label> <div class="col-sm-10"> <input type="text" name="empName" class="form-control" id="empNameModal" placeholder="Email"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">郵箱</label> <div class="col-sm-10"> <input type="text" name="email" class="form-control" id="emailModal" placeholder="Password"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">性別</label> <div class="col-sm-10"> <label class="radio-inline"> <input type="radio" name="gender" id="genderModal" value="F"> 男 </label> <label class="radio-inline"> <input type="radio" name="gender" id="genderModal" value="M"> 女 </label> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">部門</label> <div class="col-sm-5"> <select name="dId" id="dIdModal"class="form-control"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">取消</button> <button type="button" class="btn btn-primary">保存</button> </div> </div> </div> </div> <!-- 搭建顯示頁面 --> <div class="container"> <!-- 標題 --> <div class="row"> <div class="col-md-12"> <h1>SSM-CRUD</h1> </div> </div> <!-- 按鈕 --> <div class="row"> <div class="col-md-4 col-md-offset-8"> <button class="btn btn-primary" id="addEmp">新增</button> <button class="btn btn-danger">刪除</button> </div> </div> <!-- 顯示錶格數據 --> <div class="row"> <div class="col-md-12"> <table class="table table-hover" id="emps_table"> <thead> <tr> <th>#</th> <th>empName</th> <th>gender</th> <th>email</th> <th>deptName</th> <th>操做</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <!-- 顯示分頁信息 --> <div class="row"> <!--分頁文字信息 --> <div class="col-md-6" id="page_info_area"></div> <!-- 分頁條信息 --> <div class="col-md-6" id="page_nav_area"></div> </div> </div> <!-- 當頁面加載完成以後發起ajax請求得到數據 ,不清楚的看鋒利jquery教程至關的經典--> <script type="text/javascript"> $(function(){ //頁面加載完畢,去首頁得到對應的數據 to_page(1); }); //使用ajax到後臺服務器查詢數據 function to_page(pn){ $.ajax({ url:"${APP_PATH}/emps", data:"pn="+pn, type:"GET", success:function(result){ //console.log(result); //一、解析並顯示員工數據 build_emps_table(result); //二、解析並顯示分頁信息 build_page_info(result); //三、解析顯示分頁條數據 build_page_nav(result); } }); } //解析服務器返回的json數據,並在員工表中顯示出來 function build_emps_table(result){ //在構建以前先清空全部的數據 $("#emps_table tbody").empty(); //第一步:得到全部的員工數據 var emps = result.extend.pageInfo.list; //第二步:對員工數據進行遍歷顯示出來 $.each(emps,function(index,item){ var empIdTd = $("<td></td>").append(item.empId); var empNameTd = $("<td></td>").append(item.empName); var gender = item.gender == 'M'?"男":"女"; var genderTd = $("<td></td>").append(gender); var emailTd = $("<td></td>").append(item.email); var departmentNameTd = $("<td></td>").append(item.department.deptName); //添加編輯按鈕 var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn") .append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("編輯"); var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn") .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("刪除"); var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn); //將上面的table表td數據添加到tr中,這裏是一個鏈式操做 $("<tr></tr>").append(empIdTd) .append(empNameTd) .append(genderTd) .append(emailTd) .append(departmentNameTd) .append(btnTd) .appendTo("#emps_table tbody"); //"#emps_table tbody"表示選取id爲emps_table下的全部的<tbody>的元素,不清楚的看鋒利的jquery書籍至關的經典 }); } //解析顯示分頁信息 function build_page_info(result){ $("#page_info_area").empty(); $("#page_info_area").append("當前第"+result.extend.pageInfo.pageNum+"頁,"+"總共"+result.extend.pageInfo.pages+"頁,"+"總共"+ result.extend.pageInfo.total+"條記錄"); } //解析右下角的導航欄 function build_page_nav(result){ //page_nav_area $("#page_nav_area").empty(); var ul = $("<ul></ul>").addClass("pagination"); //構建元素 var firstPageLi = $("<li></li>").append($("<a></a>").append("首頁").attr("href","#")); var prePageLi = $("<li></li>").append($("<a></a>").append("«")); //判斷是否有前一頁,若是沒有前一頁就不能點擊 if(result.extend.pageInfo.hasPreviousPage == false){ firstPageLi.addClass("disabled"); prePageLi.addClass("disabled"); } //給前一頁和首頁添加按鈕點擊事件 firstPageLi.click(function(){ to_page(1); }); prePageLi.click(function(){ //跳轉到當前頁的前一頁 to_page(result.extend.pageInfo.pageNum-1); }); var nextPageLi = $("<li></li>").append($("<a></a>").append("»")); var lastPageLi = $("<li></li>").append($("<a></a>").append("末頁").attr("href","#")); //若是沒有下一頁不能被點擊 if(result.extend.pageInfo.hasNextPage == false){ nextPageLi.addClass("disabled"); lastPageLi.addClass("disabled"); } //給下一頁和尾頁添加點擊事件 nextPageLi.click(function(){ to_page(result.extend.pageInfo.pageNum+1); }); lastPageLi.click(function(){ to_page(result.extend.pageInfo.pages); }); //添加首頁和前一頁 的提示 ul.append(firstPageLi).append(prePageLi); //1,2,3遍歷給ul中添加頁碼提示 $.each(result.extend.pageInfo.navigatepageNums,function(index,item){ var numLi = $("<li></li>").append($("<a></a>").append(item)); //判斷當前遍歷的若是是當前正在顯示的頁面,應該高亮顯示 if(result.extend.pageInfo.pageNum == item){ numLi.addClass("active"); } //添加點擊事件 numLi.click(function(){ //點擊的時候從新使用ajax到服務器查詢數據 to_page(item); }); ul.append(numLi); }); //添加下一頁和末頁 的提示 ul.append(nextPageLi).append(lastPageLi); //把ul加入到nav var navEle = $("<nav></nav>").append(ul); navEle.appendTo("#page_nav_area"); } //點擊新增按鈕,彈出新增長員工的對話框 $("#addEmp").click(function(){ $('#addEmpModal').modal({ backdrop:'static' }) }); </script> </div> </body> </html>
2一、尚硅谷_SSM高級整合_新增_Ajax顯示部門信息.avijquery
對於上面的部門,咱們應該使用ajax到後天去查詢到部門的信息,而後再顯示出來
在後臺咱們新建一個部門的控制類DepartmentController.java
package com.atguigu.crud.controller; import java.util.HashMap; import java.util.List; 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.ResponseBody; import com.atguigu.crud.bean.Department; import com.atguigu.crud.bean.Msg; import com.atguigu.crud.service.DepartmentService; @Controller public class DepartmentController { @Autowired private DepartmentService service; @RequestMapping("/depts") @ResponseBody public Msg getAllDepts(){ List<Department> depts = service.getDepts(); Msg msg = new Msg(); msg.setCode(100); msg.setMsg("查找部門成功"); msg.getExtend().put("depts", depts); return msg; } }
對於的業務操做類DepartmentService.java
package com.atguigu.crud.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.atguigu.crud.bean.Department; import com.atguigu.crud.dao.DepartmentMapper; @Service public class DepartmentService { @Autowired private DepartmentMapper departmentMapper; public List<Department> getDepts(){ return departmentMapper.selectByExample(null); } }
咱們在瀏覽器輸入:http://weiyuan-pc:8080/ssm-curd/depts
就能夠查詢獲得服務器方法的部門的json數據以下
{
"code": 100,
"msg": "查找部門成功",
"extend": {
"depts": [
{
"deptId": 1,
"deptName": "研發部"
},
{
"deptId": 2,
"deptName": "測試部"
}
]
}
}
接下來咱們來看看具體的代碼git
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>員工列表</title> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <% pageContext.setAttribute("APP_PATH", request.getContextPath()); %> <!-- web路徑: 不以/開始的相對路徑,找資源,以當前資源的路徑爲基準,常常容易出問題。 以/開始的相對路徑,找資源,以服務器的路徑爲標準(http://localhost:3306);須要加上項目名 http://localhost:3306/crud --> <script type="text/javascript" src="${APP_PATH}/static/js/jquery-2.1.1.js"></script> <link href="${APP_PATH }/static/bootstrap-3.3.7/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="${APP_PATH}/static/bootstrap-3.3.7/dist/js/bootstrap.min.js"></script> </head> <body> <!-- 新增員工信息的對話框 --> <div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <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" id="myModalLabel">新增員工</h4> </div> <div class="modal-body"> <!-- 實體類的表單,表單項 的name須要給實體bean對象的一一對應起來,springmvc會幫咱們自動封裝--> <form class="form-horizontal"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">姓名</label> <div class="col-sm-10"> <input type="text" name="empName" class="form-control" id="empNameModal" placeholder="Email"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">郵箱</label> <div class="col-sm-10"> <input type="text" name="email" class="form-control" id="emailModal" placeholder="Password"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">性別</label> <div class="col-sm-10"> <label class="radio-inline"> <input type="radio" name="gender" id="genderModal" value="F"> 男 </label> <label class="radio-inline"> <input type="radio" name="gender" id="genderModal" value="M"> 女 </label> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">部門</label> <div class="col-sm-5"> <select name="dId" id="dIdModal"class="form-control"> </select> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">取消</button> <button type="button" class="btn btn-primary">保存</button> </div> </div> </div> </div> <!-- 搭建顯示頁面 --> <div class="container"> <!-- 標題 --> <div class="row"> <div class="col-md-12"> <h1>SSM-CRUD</h1> </div> </div> <!-- 按鈕 --> <div class="row"> <div class="col-md-4 col-md-offset-8"> <button class="btn btn-primary" id="addEmp">新增</button> <button class="btn btn-danger">刪除</button> </div> </div> <!-- 顯示錶格數據 --> <div class="row"> <div class="col-md-12"> <table class="table table-hover" id="emps_table"> <thead> <tr> <th>#</th> <th>empName</th> <th>gender</th> <th>email</th> <th>deptName</th> <th>操做</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <!-- 顯示分頁信息 --> <div class="row"> <!--分頁文字信息 --> <div class="col-md-6" id="page_info_area"></div> <!-- 分頁條信息 --> <div class="col-md-6" id="page_nav_area"></div> </div> </div> <!-- 當頁面加載完成以後發起ajax請求得到數據 ,不清楚的看鋒利jquery教程至關的經典--> <script type="text/javascript"> $(function(){ //頁面加載完畢,去首頁得到對應的數據 to_page(1); }); //使用ajax到後臺服務器查詢數據 function to_page(pn){ $.ajax({ url:"${APP_PATH}/emps", data:"pn="+pn, type:"GET", success:function(result){ //console.log(result); //一、解析並顯示員工數據 build_emps_table(result); //二、解析並顯示分頁信息 build_page_info(result); //三、解析顯示分頁條數據 build_page_nav(result); } }); } //解析服務器返回的json數據,並在員工表中顯示出來 function build_emps_table(result){ //在構建以前先清空全部的數據 $("#emps_table tbody").empty(); //第一步:得到全部的員工數據 var emps = result.extend.pageInfo.list; //第二步:對員工數據進行遍歷顯示出來 $.each(emps,function(index,item){ var empIdTd = $("<td></td>").append(item.empId); var empNameTd = $("<td></td>").append(item.empName); var gender = item.gender == 'M'?"男":"女"; var genderTd = $("<td></td>").append(gender); var emailTd = $("<td></td>").append(item.email); var departmentNameTd = $("<td></td>").append(item.department.deptName); //添加編輯按鈕 var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn") .append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("編輯"); var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn") .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("刪除"); var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn); //將上面的table表td數據添加到tr中,這裏是一個鏈式操做 $("<tr></tr>").append(empIdTd) .append(empNameTd) .append(genderTd) .append(emailTd) .append(departmentNameTd) .append(btnTd) .appendTo("#emps_table tbody"); //"#emps_table tbody"表示選取id爲emps_table下的全部的<tbody>的元素,不清楚的看鋒利的jquery書籍至關的經典 }); } //解析顯示分頁信息 function build_page_info(result){ $("#page_info_area").empty(); $("#page_info_area").append("當前第"+result.extend.pageInfo.pageNum+"頁,"+"總共"+result.extend.pageInfo.pages+"頁,"+"總共"+ result.extend.pageInfo.total+"條記錄"); } //解析右下角的導航欄 function build_page_nav(result){ //page_nav_area $("#page_nav_area").empty(); var ul = $("<ul></ul>").addClass("pagination"); //構建元素 var firstPageLi = $("<li></li>").append($("<a></a>").append("首頁").attr("href","#")); var prePageLi = $("<li></li>").append($("<a></a>").append("«")); //判斷是否有前一頁,若是沒有前一頁就不能點擊 if(result.extend.pageInfo.hasPreviousPage == false){ firstPageLi.addClass("disabled"); prePageLi.addClass("disabled"); } //給前一頁和首頁添加按鈕點擊事件 firstPageLi.click(function(){ to_page(1); }); prePageLi.click(function(){ //跳轉到當前頁的前一頁 to_page(result.extend.pageInfo.pageNum-1); }); var nextPageLi = $("<li></li>").append($("<a></a>").append("»")); var lastPageLi = $("<li></li>").append($("<a></a>").append("末頁").attr("href","#")); //若是沒有下一頁不能被點擊 if(result.extend.pageInfo.hasNextPage == false){ nextPageLi.addClass("disabled"); lastPageLi.addClass("disabled"); } //給下一頁和尾頁添加點擊事件 nextPageLi.click(function(){ to_page(result.extend.pageInfo.pageNum+1); }); lastPageLi.click(function(){ to_page(result.extend.pageInfo.pages); }); //添加首頁和前一頁 的提示 ul.append(firstPageLi).append(prePageLi); //1,2,3遍歷給ul中添加頁碼提示 $.each(result.extend.pageInfo.navigatepageNums,function(index,item){ var numLi = $("<li></li>").append($("<a></a>").append(item)); //判斷當前遍歷的若是是當前正在顯示的頁面,應該高亮顯示 if(result.extend.pageInfo.pageNum == item){ numLi.addClass("active"); } //添加點擊事件 numLi.click(function(){ //點擊的時候從新使用ajax到服務器查詢數據 to_page(item); }); ul.append(numLi); }); //添加下一頁和末頁 的提示 ul.append(nextPageLi).append(lastPageLi); //把ul加入到nav var navEle = $("<nav></nav>").append(ul); navEle.appendTo("#page_nav_area"); } //點擊新增按鈕,彈出新增長員工的對話框 $("#addEmp").click(function(){ var parent = $("#dIdModal"); //使用ajax請求部門的數據 $.ajax( { url:"${APP_PATH}/depts", type:"GET", success:function(result){ //對result數據進行解析添加到 var depts = result.extend.depts; $.each(depts,function(index,item){ //給option選項設置值應該是deptid var opt = $("<option></option>").append(item.deptName).attr("value",item.deptId); parent.append(opt); }); } } ); $('#addEmpModal').modal({ backdrop:'static' }) }); </script> </div> </body> </html>
2二、尚硅谷_SSM高級整合_新增_新增基本完成.avigithub
接下面咱們實現當員工點擊保存的時候,實現人員的保存,暫時不實現對輸入數據在前臺頁面和後臺的校驗web
這裏要採用restful風格的操做ajax
/emp/id 若是採用get方式 查詢id的聯繫人
/emp post方式保存聯繫人
/emp/id put方式修改聯繫人
/emp/id delete方式刪除聯繫人
這裏咱們使用ajax的方式保存聯繫人,保存聯繫人成功以後在ajax成功的回調函數中跳轉到最後一頁查看剛剛新增成功的聯繫人,跳轉到最後一頁須要從新使用ajax再次去查詢下聯繫人。
第二保存聯繫人成功以後,咱們須要關閉新建聯繫人的摸態對話框
如今咱們來看下代碼
EmployeeController.java
package com.atguigu.crud.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.atguigu.crud.bean.Employee; import com.atguigu.crud.bean.Msg; import com.atguigu.crud.dao.EmployeeMapper; import com.atguigu.crud.service.EmployeeService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; /** * * 處理員工的增刪改查操做 * */ @Controller public class EmployeeController { @Autowired private EmployeeService employeeService; /** * 負責將PageInfo對象轉化成json對象 * */ @RequestMapping("/emps") @ResponseBody public Msg getEmpsWithJson(@RequestParam(value="pn",defaultValue ="1") Integer pn) { //使用mybatis分頁插件 pn表示當前查詢的頁數,5表示每頁顯示第幾條 System.out.println("EmployeeController is called pn"+pn); PageHelper.startPage(pn, 5); //在PageHelper.startPage(pn, 5);後面的查詢語句就能夠實現分頁查詢 List<Employee> list = employeeService.getAll(); //咱們將查詢的結果封裝到PageInfo對象之中,5表示右下角導航欄的數目是5 PageInfo info = new PageInfo(list,5); Msg msg = new Msg(); msg.setCode(100); msg.setMsg("業務操做成功"); msg.getExtend().put("pageInfo", info); return msg; } /** * 這裏必定要注意採用的resetful風格,請求方式必須是post * */ @RequestMapping(value="/save",method=RequestMethod.POST) @ResponseBody public Msg save(Employee employee){ System.out.println("save is calle:"+employee.toString()); Msg msg = new Msg(); employeeService.save(employee); msg.setCode(100); msg.setMsg("保存員工數據成功"); return msg; } }
EmployeeService.java
package com.atguigu.crud.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.atguigu.crud.bean.Employee; import com.atguigu.crud.dao.EmployeeMapper; @Service public class EmployeeService { @Autowired private EmployeeMapper employeeMapper; public List<Employee> getAll(){ List<Employee> list = employeeMapper.selectByExampleWithDept(null); return list; } public void save(Employee employee) { // TODO Auto-generated method stub //這裏要注意insert和insertSelevite的區別,使用insert將會null字段插入到數據庫中。insertselct不會 //如今要實現員工的id自增加,employee中的id字段傳遞過來的值是null字段,因此不能使用insert,會將null字段插入 employeeMapper.insertSelective(employee); } }
對應的index.jsp的頁面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>員工列表</title> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <% pageContext.setAttribute("APP_PATH", request.getContextPath()); %> <!-- web路徑: 不以/開始的相對路徑,找資源,以當前資源的路徑爲基準,常常容易出問題。 以/開始的相對路徑,找資源,以服務器的路徑爲標準(http://localhost:3306);須要加上項目名 http://localhost:3306/crud --> <script type="text/javascript" src="${APP_PATH}/static/js/jquery-2.1.1.js"></script> <link href="${APP_PATH }/static/bootstrap-3.3.7/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="${APP_PATH}/static/bootstrap-3.3.7/dist/js/bootstrap.min.js"></script> </head> <body> <!-- 新增員工信息的對話框 --> <div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <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" id="myModalLabel">新增員工</h4> </div> <div class="modal-body"> <!-- 實體類的表單,表單項 的name須要給實體bean對象的一一對應起來,springmvc會幫咱們自動封裝--> <form class="form-horizontal"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">姓名</label> <div class="col-sm-10"> <input type="text" name="empName" class="form-control" id="empNameModal" placeholder="Email"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">郵箱</label> <div class="col-sm-10"> <input type="text" name="email" class="form-control" id="emailModal" placeholder="Password"> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">性別</label> <div class="col-sm-10"> <label class="radio-inline"> <input type="radio" name="gender" id="genderModal" value="F"> 男 </label> <label class="radio-inline"> <input type="radio" name="gender" id="genderModal" value="M"> 女 </label> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">部門</label> <div class="col-sm-5"> <select name="dId" id="dIdModal"class="form-control"> </select> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">取消</button> <button type="button" class="btn btn-primary" id ="saveEmp">保存</button> </div> </div> </div> </div> <!-- 搭建顯示頁面 --> <div class="container"> <!-- 標題 --> <div class="row"> <div class="col-md-12"> <h1>SSM-CRUD</h1> </div> </div> <!-- 按鈕 --> <div class="row"> <div class="col-md-4 col-md-offset-8"> <button class="btn btn-primary" id="addEmp">新增</button> <button class="btn btn-danger">刪除</button> </div> </div> <!-- 顯示錶格數據 --> <div class="row"> <div class="col-md-12"> <table class="table table-hover" id="emps_table"> <thead> <tr> <th>#</th> <th>empName</th> <th>gender</th> <th>email</th> <th>deptName</th> <th>操做</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <!-- 顯示分頁信息 --> <div class="row"> <!--分頁文字信息 --> <div class="col-md-6" id="page_info_area"></div> <!-- 分頁條信息 --> <div class="col-md-6" id="page_nav_area"></div> </div> </div> <!-- 當頁面加載完成以後發起ajax請求得到數據 ,不清楚的看鋒利jquery教程至關的經典--> <script type="text/javascript"> //定義一個全局變量,得到當前中的記錄數 var total; $(function(){ //頁面加載完畢,去首頁得到對應的數據 to_page(1); }); //使用ajax到後臺服務器查詢數據 function to_page(pn){ $.ajax({ url:"${APP_PATH}/emps", data:"pn="+pn, type:"GET", success:function(result){ //console.log(result); //一、解析並顯示員工數據 build_emps_table(result); //二、解析並顯示分頁信息 build_page_info(result); //三、解析顯示分頁條數據 build_page_nav(result); } }); } //解析服務器返回的json數據,並在員工表中顯示出來 function build_emps_table(result){ //在構建以前先清空全部的數據 $("#emps_table tbody").empty(); //第一步:得到全部的員工數據 var emps = result.extend.pageInfo.list; //第二步:對員工數據進行遍歷顯示出來 $.each(emps,function(index,item){ var empIdTd = $("<td></td>").append(item.empId); var empNameTd = $("<td></td>").append(item.empName); var gender = item.gender == 'M'?"男":"女"; var genderTd = $("<td></td>").append(gender); var emailTd = $("<td></td>").append(item.email); var departmentNameTd = $("<td></td>").append(item.department.deptName); //添加編輯按鈕 var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn") .append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("編輯"); var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn") .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("刪除"); var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn); //將上面的table表td數據添加到tr中,這裏是一個鏈式操做 $("<tr></tr>").append(empIdTd) .append(empNameTd) .append(genderTd) .append(emailTd) .append(departmentNameTd) .append(btnTd) .appendTo("#emps_table tbody"); //"#emps_table tbody"表示選取id爲emps_table下的全部的<tbody>的元素,不清楚的看鋒利的jquery書籍至關的經典 }); } //解析顯示分頁信息 function build_page_info(result){ $("#page_info_area").empty(); $("#page_info_area").append("當前第"+result.extend.pageInfo.pageNum+"頁,"+"總共"+result.extend.pageInfo.pages+"頁,"+"總共"+ result.extend.pageInfo.total+"條記錄"); total = result.extend.pageInfo.total; } //解析右下角的導航欄 function build_page_nav(result){ //page_nav_area $("#page_nav_area").empty(); var ul = $("<ul></ul>").addClass("pagination"); //構建元素 var firstPageLi = $("<li></li>").append($("<a></a>").append("首頁").attr("href","#")); var prePageLi = $("<li></li>").append($("<a></a>").append("«")); //判斷是否有前一頁,若是沒有前一頁就不能點擊 if(result.extend.pageInfo.hasPreviousPage == false){ firstPageLi.addClass("disabled"); prePageLi.addClass("disabled"); } //給前一頁和首頁添加按鈕點擊事件 firstPageLi.click(function(){ to_page(1); }); prePageLi.click(function(){ //跳轉到當前頁的前一頁 to_page(result.extend.pageInfo.pageNum-1); }); var nextPageLi = $("<li></li>").append($("<a></a>").append("»")); var lastPageLi = $("<li></li>").append($("<a></a>").append("末頁").attr("href","#")); //若是沒有下一頁不能被點擊 if(result.extend.pageInfo.hasNextPage == false){ nextPageLi.addClass("disabled"); lastPageLi.addClass("disabled"); } //給下一頁和尾頁添加點擊事件 nextPageLi.click(function(){ to_page(result.extend.pageInfo.pageNum+1); }); lastPageLi.click(function(){ to_page(result.extend.pageInfo.pages); }); //添加首頁和前一頁 的提示 ul.append(firstPageLi).append(prePageLi); //1,2,3遍歷給ul中添加頁碼提示 $.each(result.extend.pageInfo.navigatepageNums,function(index,item){ var numLi = $("<li></li>").append($("<a></a>").append(item)); //判斷當前遍歷的若是是當前正在顯示的頁面,應該高亮顯示 if(result.extend.pageInfo.pageNum == item){ numLi.addClass("active"); } //添加點擊事件 numLi.click(function(){ //點擊的時候從新使用ajax到服務器查詢數據 to_page(item); }); ul.append(numLi); }); //添加下一頁和末頁 的提示 ul.append(nextPageLi).append(lastPageLi); //把ul加入到nav var navEle = $("<nav></nav>").append(ul); navEle.appendTo("#page_nav_area"); } //點擊新增按鈕,彈出新增長員工的對話框 $("#addEmp").click(function(){ var parent = $("#dIdModal"); //使用ajax請求部門的數據 $.ajax( { url:"${APP_PATH}/depts", type:"GET", success:function(result){ //對result數據進行解析添加到 var depts = result.extend.depts; $.each(depts,function(index,item){ //給option選項設置值應該是deptid var opt = $("<option></option>").append(item.deptName).attr("value",item.deptId); parent.append(opt); }); } } ); $('#addEmpModal').modal({ backdrop:'static' }) }); //點擊保存聯繫人 $("#saveEmp").click(function(){ $.ajax({ url:"${APP_PATH}/save", data:$("#addEmpModal form").serialize(), type:"post", success:function(result){ //保存聯繫人成功須要作下面的幾件事情 //第一件事情就是讓新建聯繫人的對話框摸太框消失 $("#addEmpModal").modal('hide'); //第二個跳轉到最後一頁 //這裏如何跳轉到最後一頁了,mybatis分頁插件這裏提供了一個功能,例如如今員工總數是100人,每頁顯示5人,最大的分頁數目就是5,你若是輸入6 //也是按照最大的5來進行查詢。員工的總數確定是大於最大的分頁數目的,如今要查詢最後一頁的數據,我以員工的總數進行查詢 //使用ajax從新再查詢下最後一頁員工的數目 // to_page(total); } }); }); </script> </div> </body> </html>
補充知識點:
data:$("#addEmpModal form").serialize(),使用ajax將表單的數據提交到後臺不清楚的看鋒利的jquer教程第六章ajax的使用,至關的經典。
2三、尚硅谷_SSM高級整合_新增_jQuery前端校驗完成.avi
上面咱們完成了對新建聯繫人的添加操做,可是沒有對輸入的信息進行校驗,例如輸入的郵箱必須知足郵箱格式,輸入的姓名必須知足特定的格式,而且新建的聯繫人在後臺數據庫中不能存在
2四、尚硅谷_SSM高級整合_新增_校驗信息顯示優化.avi
Bootstrap 對錶單控件的校驗狀態,如 error、warning 和 success 狀態,都定義了樣式。使用時,添加 .has-warning
、.has-error
或 .has-success
類到這些控件的父元素便可。任何包含在此元素以內的 .control-label
、.form-control
和 .help-block
元素都將接受這些校驗狀態的樣式。
如今例如:
要實現上面的這種功能,如何實現了找到
原理就是校驗失敗的時候,給當前input的父元素添加has-error屬性,顯示文字給span元素添加help-block屬性,在添加屬性以前記得先清除掉以前的全部屬性
整個代碼以下
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>員工列表</title> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <% pageContext.setAttribute("APP_PATH", request.getContextPath()); %> <!-- web路徑: 不以/開始的相對路徑,找資源,以當前資源的路徑爲基準,常常容易出問題。 以/開始的相對路徑,找資源,以服務器的路徑爲標準(http://localhost:3306);須要加上項目名 http://localhost:3306/crud --> <script type="text/javascript" src="${APP_PATH}/static/js/jquery-2.1.1.js"></script> <link href="${APP_PATH }/static/bootstrap-3.3.7/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="${APP_PATH}/static/bootstrap-3.3.7/dist/js/bootstrap.min.js"></script> </head> <body> <!-- 新增員工信息的對話框 --> <div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <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" id="myModalLabel">新增員工</h4> </div> <div class="modal-body"> <!-- 實體類的表單,表單項 的name須要給實體bean對象的一一對應起來,springmvc會幫咱們自動封裝--> <form class="form-horizontal"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">姓名</label> <div class="col-sm-10"> <input type="text" name="empName" class="form-control" id="empNameModal" placeholder="name"> <span id="name_span" class="help-block"></span> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">郵箱</label> <div class="col-sm-10"> <input type="text" name="email" class="form-control" id="emailModal" placeholder="eamil"> <span id="email_span" class="help-block"></span> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">性別</label> <div class="col-sm-10"> <label class="radio-inline"> <input type="radio" name="gender" id="genderModal" value="F"> 男 </label> <label class="radio-inline"> <input type="radio" name="gender" id="genderModal" value="M"> 女 </label> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">部門</label> <div class="col-sm-5"> <select name="dId" id="dIdModal"class="form-control"> </select> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">取消</button> <button type="button" class="btn btn-primary" id ="saveEmp">保存</button> </div> </div> </div> </div> <!-- 搭建顯示頁面 --> <div class="container"> <!-- 標題 --> <div class="row"> <div class="col-md-12"> <h1>SSM-CRUD</h1> </div> </div> <!-- 按鈕 --> <div class="row"> <div class="col-md-4 col-md-offset-8"> <button class="btn btn-primary" id="addEmp">新增</button> <button class="btn btn-danger">刪除</button> </div> </div> <!-- 顯示錶格數據 --> <div class="row"> <div class="col-md-12"> <table class="table table-hover" id="emps_table"> <thead> <tr> <th>#</th> <th>empName</th> <th>gender</th> <th>email</th> <th>deptName</th> <th>操做</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <!-- 顯示分頁信息 --> <div class="row"> <!--分頁文字信息 --> <div class="col-md-6" id="page_info_area"></div> <!-- 分頁條信息 --> <div class="col-md-6" id="page_nav_area"></div> </div> </div> <!-- 當頁面加載完成以後發起ajax請求得到數據 ,不清楚的看鋒利jquery教程至關的經典--> <script type="text/javascript"> //定義一個全局變量,得到當前中的記錄數 var total; $(function(){ //頁面加載完畢,去首頁得到對應的數據 to_page(1); }); //使用ajax到後臺服務器查詢數據 function to_page(pn){ $.ajax({ url:"${APP_PATH}/emps", data:"pn="+pn, type:"GET", success:function(result){ //console.log(result); //一、解析並顯示員工數據 build_emps_table(result); //二、解析並顯示分頁信息 build_page_info(result); //三、解析顯示分頁條數據 build_page_nav(result); } }); } //解析服務器返回的json數據,並在員工表中顯示出來 function build_emps_table(result){ //在構建以前先清空全部的數據 $("#emps_table tbody").empty(); //第一步:得到全部的員工數據 var emps = result.extend.pageInfo.list; //第二步:對員工數據進行遍歷顯示出來 $.each(emps,function(index,item){ var empIdTd = $("<td></td>").append(item.empId); var empNameTd = $("<td></td>").append(item.empName); var gender = item.gender == 'M'?"男":"女"; var genderTd = $("<td></td>").append(gender); var emailTd = $("<td></td>").append(item.email); var departmentNameTd = $("<td></td>").append(item.department.deptName); //添加編輯按鈕 var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn") .append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("編輯"); var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn") .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("刪除"); var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn); //將上面的table表td數據添加到tr中,這裏是一個鏈式操做 $("<tr></tr>").append(empIdTd) .append(empNameTd) .append(genderTd) .append(emailTd) .append(departmentNameTd) .append(btnTd) .appendTo("#emps_table tbody"); //"#emps_table tbody"表示選取id爲emps_table下的全部的<tbody>的元素,不清楚的看鋒利的jquery書籍至關的經典 }); } //解析顯示分頁信息 function build_page_info(result){ $("#page_info_area").empty(); $("#page_info_area").append("當前第"+result.extend.pageInfo.pageNum+"頁,"+"總共"+result.extend.pageInfo.pages+"頁,"+"總共"+ result.extend.pageInfo.total+"條記錄"); total = result.extend.pageInfo.total; } //解析右下角的導航欄 function build_page_nav(result){ //page_nav_area $("#page_nav_area").empty(); var ul = $("<ul></ul>").addClass("pagination"); //構建元素 var firstPageLi = $("<li></li>").append($("<a></a>").append("首頁").attr("href","#")); var prePageLi = $("<li></li>").append($("<a></a>").append("«")); //判斷是否有前一頁,若是沒有前一頁就不能點擊 if(result.extend.pageInfo.hasPreviousPage == false){ firstPageLi.addClass("disabled"); prePageLi.addClass("disabled"); } //給前一頁和首頁添加按鈕點擊事件 firstPageLi.click(function(){ to_page(1); }); prePageLi.click(function(){ //跳轉到當前頁的前一頁 to_page(result.extend.pageInfo.pageNum-1); }); var nextPageLi = $("<li></li>").append($("<a></a>").append("»")); var lastPageLi = $("<li></li>").append($("<a></a>").append("末頁").attr("href","#")); //若是沒有下一頁不能被點擊 if(result.extend.pageInfo.hasNextPage == false){ nextPageLi.addClass("disabled"); lastPageLi.addClass("disabled"); } //給下一頁和尾頁添加點擊事件 nextPageLi.click(function(){ to_page(result.extend.pageInfo.pageNum+1); }); lastPageLi.click(function(){ to_page(result.extend.pageInfo.pages); }); //添加首頁和前一頁 的提示 ul.append(firstPageLi).append(prePageLi); //1,2,3遍歷給ul中添加頁碼提示 $.each(result.extend.pageInfo.navigatepageNums,function(index,item){ var numLi = $("<li></li>").append($("<a></a>").append(item)); //判斷當前遍歷的若是是當前正在顯示的頁面,應該高亮顯示 if(result.extend.pageInfo.pageNum == item){ numLi.addClass("active"); } //添加點擊事件 numLi.click(function(){ //點擊的時候從新使用ajax到服務器查詢數據 to_page(item); }); ul.append(numLi); }); //添加下一頁和末頁 的提示 ul.append(nextPageLi).append(lastPageLi); //把ul加入到nav var navEle = $("<nav></nav>").append(ul); navEle.appendTo("#page_nav_area"); } //點擊新增按鈕,彈出新增長員工的對話框 $("#addEmp").click(function(){ var parent = $("#dIdModal"); //使用ajax請求部門的數據 $.ajax( { url:"${APP_PATH}/depts", type:"GET", success:function(result){ //對result數據進行解析添加到 var depts = result.extend.depts; $.each(depts,function(index,item){ //給option選項設置值應該是deptid var opt = $("<option></option>").append(item.deptName).attr("value",item.deptId); parent.append(opt); }); } } ); $('#addEmpModal').modal({ backdrop:'static' }) }); //點擊保存聯繫人 $("#saveEmp").click(function(){ //首先判斷輸入的參數是否知足規則 if(!validate_add_form()){ return false; } $.ajax({ url:"${APP_PATH}/save", data:$("#addEmpModal form").serialize(), type:"post", success:function(result){ //保存聯繫人成功須要作下面的幾件事情 //第一件事情就是讓新建聯繫人的對話框摸太框消失 $("#addEmpModal").modal('hide'); //第二個跳轉到最後一頁 //這裏如何跳轉到最後一頁了,mybatis分頁插件這裏提供了一個功能,例如如今員工總數是100人,每頁顯示5人,最大的分頁數目就是5,你若是輸入6 //也是按照最大的5來進行查詢。員工的總數確定是大於最大的分頁數目的,如今要查詢最後一頁的數據,我以員工的總數進行查詢 //使用ajax從新再查詢下最後一頁員工的數目 // to_page(total); } }); }); //juqery前臺校驗數據 //校驗表單數據 function validate_add_form(){ //一、拿到要校驗的數據,使用正則表達式 var empName = $("#empNameModal").val(); var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/; if(!regName.test(empName)){ //添加元素狀態以前。先清空清除當前元素的校驗狀態 $("#empNameModal").parent().removeClass("has-success has-error"); $("#name_span").next("span").text(""); //給當前節點的父元素添加has-error屬性 $("#empNameModal").parent().addClass("has-error"); //給span節點添加.help-block屬性 $("#name_span").addClass("help-block").text("姓名格式不正確"); return false; }else{ $("#empNameModal").parent().removeClass("has-success has-error"); $("#name_span").next("span").text(""); //給當前節點的父元素添加has-error屬性 $("#empNameModal").parent().addClass("has-success"); //給span節點添加.help-block屬性 $("#name_span").addClass("help-block").text(""); }; //二、校驗郵箱信息 var email = $("#emailModal").val(); var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/; if(!regEmail.test(email)){ $("#emailModal").parent().removeClass("has-success has-error"); $("#email_span").next("span").text(""); $("#emailModal").parent().addClass("has-error"); //給span節點添加.help-block屬性 $("#email_span").addClass("help-block").text("郵箱格式不正確"); return false; }else{ $("#emailModal").parent().removeClass("has-success has-error"); $("#email_span").next("span").text(""); $("#emailModal").parent().addClass("has-success"); //給span節點添加.help-block屬性 $("#email_span").addClass("help-block").text(""); } return true; } </script> </div> </body> </html>
2五、尚硅谷_SSM高級整合_新增_Ajax校驗用戶名是否重複.avi
接下來實現下面的功能,當點擊保存的時候校驗當前的用戶在後臺數據庫中是否已經存在了,要使用ajax功能
應該給員工姓名的輸入框當輸入的姓名發送改變的時候使用ajax校驗當前用戶名是否可用
,若是當前用戶不可用,在對應的父節點和<span>節點中添加has-error屬性和help-block提示當時用戶已經存在,
第二:若是當前用戶存在,點擊保存按鈕的時候,沒法保存數據
第三:這裏還須要一個主意點的是每次點擊新增聯繫人,彈出新增聯繫人摸態框界面的時候,都已經將數據清空
這裏能夠將jquery對象轉化成docment對象,調用docment對象的rese函數,不清楚的看鋒利jquery教程
EmployeeController.java
package com.atguigu.crud.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.atguigu.crud.bean.Employee; import com.atguigu.crud.bean.Msg; import com.atguigu.crud.dao.EmployeeMapper; import com.atguigu.crud.service.EmployeeService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; /** * * 處理員工的增刪改查操做 * */ @Controller public class EmployeeController { @Autowired private EmployeeService employeeService; /** * 負責將PageInfo對象轉化成json對象 * */ @RequestMapping("/emps") @ResponseBody public Msg getEmpsWithJson(@RequestParam(value="pn",defaultValue ="1") Integer pn) { //使用mybatis分頁插件 pn表示當前查詢的頁數,5表示每頁顯示第幾條 System.out.println("EmployeeController is called pn"+pn); PageHelper.startPage(pn, 5); //在PageHelper.startPage(pn, 5);後面的查詢語句就能夠實現分頁查詢 List<Employee> list = employeeService.getAll(); //咱們將查詢的結果封裝到PageInfo對象之中,5表示右下角導航欄的數目是5 PageInfo info = new PageInfo(list,5); Msg msg = new Msg(); msg.setCode(100); msg.setMsg("業務操做成功"); msg.getExtend().put("pageInfo", info); return msg; } /** * 這裏必定要注意採用的resetful風格,請求方式必須是post * */ @RequestMapping(value="/save",method=RequestMethod.POST) @ResponseBody public Msg save(Employee employee){ System.out.println("save is calle:"+employee.toString()); Msg msg = new Msg(); employeeService.save(employee); msg.setCode(100); msg.setMsg("保存員工數據成功"); return msg; } @RequestMapping("/isUserExist") @ResponseBody public Msg isUserExist(@RequestParam("empName") String empName){ System.out.println("isUserExist is called:"+empName); Msg msg = new Msg(); Boolean exits = employeeService.isUserExist(empName); if(exits){ //200表示聯繫人已經存在 msg.setCode(200); }else{ //100表示聯繫人可用 msg.setCode(100); } return msg; } }
EmployeeService.java
package com.atguigu.crud.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.atguigu.crud.bean.Employee; import com.atguigu.crud.bean.EmployeeExample; import com.atguigu.crud.bean.EmployeeExample.Criteria; import com.atguigu.crud.dao.EmployeeMapper; @Service public class EmployeeService { @Autowired private EmployeeMapper employeeMapper; public List<Employee> getAll(){ List<Employee> list = employeeMapper.selectByExampleWithDept(null); return list; } public void save(Employee employee) { // TODO Auto-generated method stub //這裏要注意insert和insertSelevite的區別,使用insert將會null字段插入到數據庫中。insertselct不會 //如今要實現員工的id自增加,employee中的id字段傳遞過來的值是null字段,因此不能使用insert,會將null字段插入 employeeMapper.insertSelective(employee); } public Boolean isUserExist(String empName) { // TODO Auto-generated method stub //採用mybatis的高級查找功能,判斷當前用戶是否存在 /*** * MyBatis的Mapper接口以及Example的實例函數及詳解 * mybatis的逆向工程中會生成實例及實例對應的example,example用於添加條件,至關where後面的部分 xxxExample example = new xxxExample(); Criteria criteria = new Example().createCriteria(); User user = XxxMapper.selectByPrimaryKey(100); //至關於select * from user where id = 100 * */ EmployeeExample example = new EmployeeExample(); Criteria createCriteria = example.createCriteria(); createCriteria.andEmpNameEqualTo(empName); long countByExample = employeeMapper.countByExample(example); if(countByExample > 0){ return true; }else{ return false; } } }
index.jsp頁面的代碼爲
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>員工列表</title> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <% pageContext.setAttribute("APP_PATH", request.getContextPath()); %> <!-- web路徑: 不以/開始的相對路徑,找資源,以當前資源的路徑爲基準,常常容易出問題。 以/開始的相對路徑,找資源,以服務器的路徑爲標準(http://localhost:3306);須要加上項目名 http://localhost:3306/crud --> <script type="text/javascript" src="${APP_PATH}/static/js/jquery-2.1.1.js"></script> <link href="${APP_PATH }/static/bootstrap-3.3.7/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="${APP_PATH}/static/bootstrap-3.3.7/dist/js/bootstrap.min.js"></script> </head> <body> <!-- 新增員工信息的對話框 --> <div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <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" id="myModalLabel">新增員工</h4> </div> <div class="modal-body"> <!-- 實體類的表單,表單項 的name須要給實體bean對象的一一對應起來,springmvc會幫咱們自動封裝--> <form class="form-horizontal"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">姓名</label> <div class="col-sm-10"> <input type="text" name="empName" class="form-control" id="empNameModal" placeholder="name"> <span id="name_span" class="help-block"></span> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">郵箱</label> <div class="col-sm-10"> <input type="text" name="email" class="form-control" id="emailModal" placeholder="eamil"> <span id="email_span" class="help-block"></span> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">性別</label> <div class="col-sm-10"> <label class="radio-inline"> <input type="radio" name="gender" id="genderModal" value="F"> 男 </label> <label class="radio-inline"> <input type="radio" name="gender" id="genderModal" value="M"> 女 </label> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">部門</label> <div class="col-sm-5"> <select name="dId" id="dIdModal"class="form-control"> </select> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">取消</button> <button type="button" class="btn btn-primary" id ="saveEmp">保存</button> </div> </div> </div> </div> <!-- 搭建顯示頁面 --> <div class="container"> <!-- 標題 --> <div class="row"> <div class="col-md-12"> <h1>SSM-CRUD</h1> </div> </div> <!-- 按鈕 --> <div class="row"> <div class="col-md-4 col-md-offset-8"> <button class="btn btn-primary" id="addEmp">新增</button> <button class="btn btn-danger">刪除</button> </div> </div> <!-- 顯示錶格數據 --> <div class="row"> <div class="col-md-12"> <table class="table table-hover" id="emps_table"> <thead> <tr> <th>#</th> <th>empName</th> <th>gender</th> <th>email</th> <th>deptName</th> <th>操做</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <!-- 顯示分頁信息 --> <div class="row"> <!--分頁文字信息 --> <div class="col-md-6" id="page_info_area"></div> <!-- 分頁條信息 --> <div class="col-md-6" id="page_nav_area"></div> </div> </div> <!-- 當頁面加載完成以後發起ajax請求得到數據 ,不清楚的看鋒利jquery教程至關的經典--> <script type="text/javascript"> //定義一個全局變量,得到當前中的記錄數 var total; $(function(){ //頁面加載完畢,去首頁得到對應的數據 to_page(1); }); //使用ajax到後臺服務器查詢數據 function to_page(pn){ $.ajax({ url:"${APP_PATH}/emps", data:"pn="+pn, type:"GET", success:function(result){ //console.log(result); //一、解析並顯示員工數據 build_emps_table(result); //二、解析並顯示分頁信息 build_page_info(result); //三、解析顯示分頁條數據 build_page_nav(result); } }); } //解析服務器返回的json數據,並在員工表中顯示出來 function build_emps_table(result){ //在構建以前先清空全部的數據 $("#emps_table tbody").empty(); //第一步:得到全部的員工數據 var emps = result.extend.pageInfo.list; //第二步:對員工數據進行遍歷顯示出來 $.each(emps,function(index,item){ var empIdTd = $("<td></td>").append(item.empId); var empNameTd = $("<td></td>").append(item.empName); var gender = item.gender == 'M'?"男":"女"; var genderTd = $("<td></td>").append(gender); var emailTd = $("<td></td>").append(item.email); var departmentNameTd = $("<td></td>").append(item.department.deptName); //添加編輯按鈕 var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn") .append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("編輯"); var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn") .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("刪除"); var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn); //將上面的table表td數據添加到tr中,這裏是一個鏈式操做 $("<tr></tr>").append(empIdTd) .append(empNameTd) .append(genderTd) .append(emailTd) .append(departmentNameTd) .append(btnTd) .appendTo("#emps_table tbody"); //"#emps_table tbody"表示選取id爲emps_table下的全部的<tbody>的元素,不清楚的看鋒利的jquery書籍至關的經典 }); } //解析顯示分頁信息 function build_page_info(result){ $("#page_info_area").empty(); $("#page_info_area").append("當前第"+result.extend.pageInfo.pageNum+"頁,"+"總共"+result.extend.pageInfo.pages+"頁,"+"總共"+ result.extend.pageInfo.total+"條記錄"); total = result.extend.pageInfo.total; } //解析右下角的導航欄 function build_page_nav(result){ //page_nav_area $("#page_nav_area").empty(); var ul = $("<ul></ul>").addClass("pagination"); //構建元素 var firstPageLi = $("<li></li>").append($("<a></a>").append("首頁").attr("href","#")); var prePageLi = $("<li></li>").append($("<a></a>").append("«")); //判斷是否有前一頁,若是沒有前一頁就不能點擊 if(result.extend.pageInfo.hasPreviousPage == false){ firstPageLi.addClass("disabled"); prePageLi.addClass("disabled"); } //給前一頁和首頁添加按鈕點擊事件 firstPageLi.click(function(){ to_page(1); }); prePageLi.click(function(){ //跳轉到當前頁的前一頁 to_page(result.extend.pageInfo.pageNum-1); }); var nextPageLi = $("<li></li>").append($("<a></a>").append("»")); var lastPageLi = $("<li></li>").append($("<a></a>").append("末頁").attr("href","#")); //若是沒有下一頁不能被點擊 if(result.extend.pageInfo.hasNextPage == false){ nextPageLi.addClass("disabled"); lastPageLi.addClass("disabled"); } //給下一頁和尾頁添加點擊事件 nextPageLi.click(function(){ to_page(result.extend.pageInfo.pageNum+1); }); lastPageLi.click(function(){ to_page(result.extend.pageInfo.pages); }); //添加首頁和前一頁 的提示 ul.append(firstPageLi).append(prePageLi); //1,2,3遍歷給ul中添加頁碼提示 $.each(result.extend.pageInfo.navigatepageNums,function(index,item){ var numLi = $("<li></li>").append($("<a></a>").append(item)); //判斷當前遍歷的若是是當前正在顯示的頁面,應該高亮顯示 if(result.extend.pageInfo.pageNum == item){ numLi.addClass("active"); } //添加點擊事件 numLi.click(function(){ //點擊的時候從新使用ajax到服務器查詢數據 to_page(item); }); ul.append(numLi); }); //添加下一頁和末頁 的提示 ul.append(nextPageLi).append(lastPageLi); //把ul加入到nav var navEle = $("<nav></nav>").append(ul); navEle.appendTo("#page_nav_area"); } //點擊新增按鈕,彈出新增長員工的對話框 $("#addEmp").click(function(){ //首先清空頁面的全部數據 //將jquery對象轉化成docment對象,調用docment對象的reset方法 $("#addEmpModal form")[0].reset(); $("#name_span").text(""); $("#empNameModal").parent().removeClass("has-success has-error"); var parent = $("#dIdModal"); //使用ajax請求部門的數據 $.ajax( { url:"${APP_PATH}/depts", type:"GET", success:function(result){ //對result數據進行解析添加到 var depts = result.extend.depts; $.each(depts,function(index,item){ //給option選項設置值應該是deptid var opt = $("<option></option>").append(item.deptName).attr("value",item.deptId); parent.append(opt); }); } } ); $('#addEmpModal').modal({ backdrop:'static' }) }); //點擊保存聯繫人 $("#saveEmp").click(function(){ //判斷當前的聯繫人是否可用 if( $(this).attr("isUserExist")=="yes"){ return false; } //首先判斷輸入的參數是否知足規則 if(!validate_add_form()){ return false; } $.ajax({ url:"${APP_PATH}/save", data:$("#addEmpModal form").serialize(), type:"post", success:function(result){ //保存聯繫人成功須要作下面的幾件事情 //第一件事情就是讓新建聯繫人的對話框摸太框消失 $("#addEmpModal").modal('hide'); //第二個跳轉到最後一頁 //這裏如何跳轉到最後一頁了,mybatis分頁插件這裏提供了一個功能,例如如今員工總數是100人,每頁顯示5人,最大的分頁數目就是5,你若是輸入6 //也是按照最大的5來進行查詢。員工的總數確定是大於最大的分頁數目的,如今要查詢最後一頁的數據,我以員工的總數進行查詢 //使用ajax從新再查詢下最後一頁員工的數目 // to_page(total); } }); }); //juqery前臺校驗數據 //校驗表單數據 function validate_add_form(){ //一、拿到要校驗的數據,使用正則表達式 var empName = $("#empNameModal").val(); var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/; if(!regName.test(empName)){ //添加元素狀態以前。先清空清除當前元素的校驗狀態 $("#empNameModal").parent().removeClass("has-success has-error"); $("#name_span").text(""); //給當前節點的父元素添加has-error屬性 $("#empNameModal").parent().addClass("has-error"); //給span節點添加.help-block屬性 $("#name_span").addClass("help-block").text("姓名格式不正確"); return false; }else{ $("#empNameModal").parent().removeClass("has-success has-error"); $("#name_span").text(""); //給當前節點的父元素添加has-error屬性 $("#empNameModal").parent().addClass("has-success"); //給span節點添加.help-block屬性 $("#name_span").addClass("help-block").text(""); }; //二、校驗郵箱信息 var email = $("#emailModal").val(); var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/; if(!regEmail.test(email)){ $("#emailModal").parent().removeClass("has-success has-error"); $("#email_span").text(""); $("#emailModal").parent().addClass("has-error"); //給span節點添加.help-block屬性 $("#email_span").addClass("help-block").text("郵箱格式不正確"); return false; }else{ $("#emailModal").parent().removeClass("has-success has-error"); $("#email_span").text(""); $("#emailModal").parent().addClass("has-success"); //給span節點添加.help-block屬性 $("#email_span").addClass("help-block").text(""); } return true; } //給輸入聯繫人的input添加change事件,判斷當前聯繫人是否可用 $("#empNameModal").change(function(){ //this表示當前操做的對象,是docment類型 //得到當前輸入的name的值 var name=$(this).val(); $.ajax({ url:"${APP_PATH}/isUserExist", type:"post", data:"empName="+name, success:function(result){ if(result.code == 200){ //說明該聯繫人已經在後臺存在不能夠 //添加元素狀態以前。先清空清除當前元素的校驗狀態 $("#empNameModal").parent().removeClass("has-success has-error"); $("#name_span").text(""); //給當前節點的父元素添加has-error屬性 $("#empNameModal").parent().addClass("has-error"); //給span節點添加.help-block屬性 $("#name_span").addClass("help-block").text("該聯繫人已經存在"); //若是當前聯繫人已經存在,點擊保存聯繫人案例的時候,就會失敗,咱們給保存聯繫人的按鈕添加一個自定義屬性用來標識當前添加的聯繫人是否存在 $("#saveEmp").attr("isUserExist","yes"); }else{ //說明該聯繫人可用 $("#empNameModal").parent().removeClass("has-success has-error"); $("#name_span").text(""); //給當前節點的父元素添加has-error屬性 $("#empNameModal").parent().addClass("has-success"); //給span節點添加.help-block屬性 $("#name_span").addClass("help-block").text("該聯繫人可用"); $("#saveEmp").attr("isUserExist","no"); } } }); }); </script> </div> </body> </html>
整個工程的目錄結構爲:
2七、尚硅谷_SSM高級整合_新增_JSR303校驗.avi
對於前段的任何校驗,用戶均可以繞過前端的校驗,例如瀏覽器去掉校驗的js,對於關鍵的數據,爲了保證安全性都必須在後端進行校驗,用戶均可以繞過給後臺發送非法數據,重要的數據爲了保證安全性,都必須進行後端校驗。
接下來咱們在後端咱們可使用jrs303校驗
使用jrs303數據校驗,須要導入下面的jar
<!--JSR303數據校驗支持;tomcat7及以上的服務器,
tomcat7如下的服務器:el表達式。額外給服務器的lib包中替換新的標準的el
-->
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.1.Final</version>
</dependency>
咱們要使用jrs3030校驗,本身在咱們須要校驗的javabean字段上面進行
@NotNull
@Size(min = 5,max = 10,message = "用戶名長度5到10")
private String username;
@NotNull
@Size(min = 5,max = 10,message = "密碼長度5到10")
private String password;
咱們這裏使用的是自定義的正則表達式,以下形式
package com.atguigu.crud.bean; import javax.validation.constraints.Pattern; public class Employee { private Integer empId; @Pattern(regexp="(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\\u9FFF]{2,5})",message="用戶名必須是2-6位中文或者6-16位的數字和英文的組合") private String empName; private String gender; @Pattern(regexp="^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$",message="郵箱格式不正確") private String email; private Integer dId; //但願查詢員工的同時部門信息也是查詢好的 private Department department; public Employee() { super(); } public Employee(Integer empId, String empName, String gender, String email, Integer dId) { super(); this.empId = empId; this.empName = empName; this.gender = gender; this.email = email; this.dId = dId; } public Department getDepartment() { return department; } public void setDepartment(Department department) { this.department = department; } public Integer getEmpId() { return empId; } public void setEmpId(Integer empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName == null ? null : empName.trim(); } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender == null ? null : gender.trim(); } public String getEmail() { return email; } public void setEmail(String email) { this.email = email == null ? null : email.trim(); } public Integer getdId() { return dId; } public void setdId(Integer dId) { this.dId = dId; } @Override public String toString() { return "Employee [empId=" + empId + ", empName=" + empName + ", gender=" + gender + ", email=" + email + ", dId=" + dId + ", department=" + department + "]"; } }
這裏有兩個地方須要注意的:爲了保證前端和後端校驗規則儘可能保證一致性,咱們要使用相同的校驗規則,可是在使用的時候要當心一點
對於jsp:校驗規則是
var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
在java代碼使用的時候,必須把先後的/去掉,第二點是校驗規則中使用到的\,在java代碼中使用\\代替,不然會出現問題
regexp="^([a-z0-9_\\.-]+)@([\\da-z\\.-]+)\\.([a-z\\.]{2,6})$"
而後再控制端如何使用校驗了,值須要在控制器端須要使用的方法中使用@valid和BindingResult就能夠了
咱們來看下代碼:
EmployeeController.java
package com.atguigu.crud.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.atguigu.crud.bean.Employee; import com.atguigu.crud.bean.Msg; import com.atguigu.crud.dao.EmployeeMapper; import com.atguigu.crud.service.EmployeeService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; /** * * 處理員工的增刪改查操做 * */ @Controller public class EmployeeController { @Autowired private EmployeeService employeeService; /** * 負責將PageInfo對象轉化成json對象 * */ @RequestMapping("/emps") @ResponseBody public Msg getEmpsWithJson(@RequestParam(value="pn",defaultValue ="1") Integer pn) { //使用mybatis分頁插件 pn表示當前查詢的頁數,5表示每頁顯示第幾條 System.out.println("EmployeeController is called pn"+pn); PageHelper.startPage(pn, 5); //在PageHelper.startPage(pn, 5);後面的查詢語句就能夠實現分頁查詢 List<Employee> list = employeeService.getAll(); //咱們將查詢的結果封裝到PageInfo對象之中,5表示右下角導航欄的數目是5 PageInfo info = new PageInfo(list,5); Msg msg = new Msg(); msg.setCode(100); msg.setMsg("業務操做成功"); msg.getExtend().put("pageInfo", info); return msg; } /** * 這裏必定要注意採用的resetful風格,請求方式必須是post * */ @RequestMapping(value="/save",method=RequestMethod.POST) @ResponseBody public Msg save(@Valid Employee employee,BindingResult result){ System.out.println("save is calle:"+employee.toString()); //這裏首先要判斷用戶輸入的參數是否合法 Map<String,Object> err_map = new HashMap<String, Object>(); Msg msg = new Msg(); if(result.hasErrors()){ List<FieldError> errors = result.getFieldErrors(); for( FieldError error: errors){ System.out.println("錯誤的字段是:"+error.getField()); System.out.println("錯誤的消息是:"+error.getDefaultMessage()); err_map.put(error.getField(), error.getDefaultMessage()); } msg.setCode(200); msg.setMsg("員工保存失敗"); msg.getExtend().put("err_map", err_map); }else{ employeeService.save(employee); msg.setCode(100); msg.setMsg("保存員工數據成功"); } return msg; } @RequestMapping("/isUserExist") @ResponseBody public Msg isUserExist(@RequestParam("empName") String empName){ System.out.println("isUserExist is called:"+empName); Msg msg = new Msg(); Boolean exits = employeeService.isUserExist(empName); if(exits){ //200表示聯繫人已經存在 msg.setCode(200); }else{ //100表示聯繫人可用 msg.setCode(100); } return msg; } }
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>員工列表</title> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <% pageContext.setAttribute("APP_PATH", request.getContextPath()); %> <!-- web路徑: 不以/開始的相對路徑,找資源,以當前資源的路徑爲基準,常常容易出問題。 以/開始的相對路徑,找資源,以服務器的路徑爲標準(http://localhost:3306);須要加上項目名 http://localhost:3306/crud --> <script type="text/javascript" src="${APP_PATH}/static/js/jquery-2.1.1.js"></script> <link href="${APP_PATH }/static/bootstrap-3.3.7/dist/css/bootstrap.min.css" rel="stylesheet"> <script src="${APP_PATH}/static/bootstrap-3.3.7/dist/js/bootstrap.min.js"></script> </head> <body> <!-- 新增員工信息的對話框 --> <div class="modal fade" id="addEmpModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <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" id="myModalLabel">新增員工</h4> </div> <div class="modal-body"> <!-- 實體類的表單,表單項 的name須要給實體bean對象的一一對應起來,springmvc會幫咱們自動封裝--> <form class="form-horizontal"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">姓名</label> <div class="col-sm-10"> <input type="text" name="empName" class="form-control" id="empNameModal" placeholder="name"> <span id="name_span" class="help-block"></span> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">郵箱</label> <div class="col-sm-10"> <input type="text" name="email" class="form-control" id="emailModal" placeholder="eamil"> <span id="email_span" class="help-block"></span> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">性別</label> <div class="col-sm-10"> <label class="radio-inline"> <input type="radio" name="gender" id="genderModal" value="F"> 男 </label> <label class="radio-inline"> <input type="radio" name="gender" id="genderModal" value="M"> 女 </label> </div> </div> <div class="form-group"> <label for="inputPassword3" class="col-sm-2 control-label">部門</label> <div class="col-sm-5"> <select name="dId" id="dIdModal"class="form-control"> </select> </div> </div> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">取消</button> <button type="button" class="btn btn-primary" id ="saveEmp">保存</button> </div> </div> </div> </div> <!-- 搭建顯示頁面 --> <div class="container"> <!-- 標題 --> <div class="row"> <div class="col-md-12"> <h1>SSM-CRUD</h1> </div> </div> <!-- 按鈕 --> <div class="row"> <div class="col-md-4 col-md-offset-8"> <button class="btn btn-primary" id="addEmp">新增</button> <button class="btn btn-danger">刪除</button> </div> </div> <!-- 顯示錶格數據 --> <div class="row"> <div class="col-md-12"> <table class="table table-hover" id="emps_table"> <thead> <tr> <th>#</th> <th>empName</th> <th>gender</th> <th>email</th> <th>deptName</th> <th>操做</th> </tr> </thead> <tbody> </tbody> </table> </div> </div> <!-- 顯示分頁信息 --> <div class="row"> <!--分頁文字信息 --> <div class="col-md-6" id="page_info_area"></div> <!-- 分頁條信息 --> <div class="col-md-6" id="page_nav_area"></div> </div> </div> <!-- 當頁面加載完成以後發起ajax請求得到數據 ,不清楚的看鋒利jquery教程至關的經典--> <script type="text/javascript"> //定義一個全局變量,得到當前中的記錄數 var total; $(function(){ //頁面加載完畢,去首頁得到對應的數據 to_page(1); }); //使用ajax到後臺服務器查詢數據 function to_page(pn){ $.ajax({ url:"${APP_PATH}/emps", data:"pn="+pn, type:"GET", success:function(result){ //console.log(result); //一、解析並顯示員工數據 build_emps_table(result); //二、解析並顯示分頁信息 build_page_info(result); //三、解析顯示分頁條數據 build_page_nav(result); } }); } //解析服務器返回的json數據,並在員工表中顯示出來 function build_emps_table(result){ //在構建以前先清空全部的數據 $("#emps_table tbody").empty(); //第一步:得到全部的員工數據 var emps = result.extend.pageInfo.list; //第二步:對員工數據進行遍歷顯示出來 $.each(emps,function(index,item){ var empIdTd = $("<td></td>").append(item.empId); var empNameTd = $("<td></td>").append(item.empName); var gender = item.gender == 'M'?"男":"女"; var genderTd = $("<td></td>").append(gender); var emailTd = $("<td></td>").append(item.email); var departmentNameTd = $("<td></td>").append(item.department.deptName); //添加編輯按鈕 var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm edit_btn") .append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("編輯"); var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm delete_btn") .append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("刪除"); var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn); //將上面的table表td數據添加到tr中,這裏是一個鏈式操做 $("<tr></tr>").append(empIdTd) .append(empNameTd) .append(genderTd) .append(emailTd) .append(departmentNameTd) .append(btnTd) .appendTo("#emps_table tbody"); //"#emps_table tbody"表示選取id爲emps_table下的全部的<tbody>的元素,不清楚的看鋒利的jquery書籍至關的經典 }); } //解析顯示分頁信息 function build_page_info(result){ $("#page_info_area").empty(); $("#page_info_area").append("當前第"+result.extend.pageInfo.pageNum+"頁,"+"總共"+result.extend.pageInfo.pages+"頁,"+"總共"+ result.extend.pageInfo.total+"條記錄"); total = result.extend.pageInfo.total; } //解析右下角的導航欄 function build_page_nav(result){ //page_nav_area $("#page_nav_area").empty(); var ul = $("<ul></ul>").addClass("pagination"); //構建元素 var firstPageLi = $("<li></li>").append($("<a></a>").append("首頁").attr("href","#")); var prePageLi = $("<li></li>").append($("<a></a>").append("«")); //判斷是否有前一頁,若是沒有前一頁就不能點擊 if(result.extend.pageInfo.hasPreviousPage == false){ firstPageLi.addClass("disabled"); prePageLi.addClass("disabled"); } //給前一頁和首頁添加按鈕點擊事件 firstPageLi.click(function(){ to_page(1); }); prePageLi.click(function(){ //跳轉到當前頁的前一頁 to_page(result.extend.pageInfo.pageNum-1); }); var nextPageLi = $("<li></li>").append($("<a></a>").append("»")); var lastPageLi = $("<li></li>").append($("<a></a>").append("末頁").attr("href","#")); //若是沒有下一頁不能被點擊 if(result.extend.pageInfo.hasNextPage == false){ nextPageLi.addClass("disabled"); lastPageLi.addClass("disabled"); } //給下一頁和尾頁添加點擊事件 nextPageLi.click(function(){ to_page(result.extend.pageInfo.pageNum+1); }); lastPageLi.click(function(){ to_page(result.extend.pageInfo.pages); }); //添加首頁和前一頁 的提示 ul.append(firstPageLi).append(prePageLi); //1,2,3遍歷給ul中添加頁碼提示 $.each(result.extend.pageInfo.navigatepageNums,function(index,item){ var numLi = $("<li></li>").append($("<a></a>").append(item)); //判斷當前遍歷的若是是當前正在顯示的頁面,應該高亮顯示 if(result.extend.pageInfo.pageNum == item){ numLi.addClass("active"); } //添加點擊事件 numLi.click(function(){ //點擊的時候從新使用ajax到服務器查詢數據 to_page(item); }); ul.append(numLi); }); //添加下一頁和末頁 的提示 ul.append(nextPageLi).append(lastPageLi); //把ul加入到nav var navEle = $("<nav></nav>").append(ul); navEle.appendTo("#page_nav_area"); } //點擊新增按鈕,彈出新增長員工的對話框 $("#addEmp").click(function(){ //首先清空頁面的全部數據 //將jquery對象轉化成docment對象,調用docment對象的reset方法 $("#addEmpModal form")[0].reset(); $("#name_span").text(""); $("#empNameModal").parent().removeClass("has-success has-error"); var parent = $("#dIdModal"); //使用ajax請求部門的數據 $.ajax( { url:"${APP_PATH}/depts", type:"GET", success:function(result){ //對result數據進行解析添加到 var depts = result.extend.depts; $.each(depts,function(index,item){ //給option選項設置值應該是deptid var opt = $("<option></option>").append(item.deptName).attr("value",item.deptId); parent.append(opt); }); } } ); $('#addEmpModal').modal({ backdrop:'static' }) }); //點擊保存聯繫人 $("#saveEmp").click(function(){ //判斷當前的聯繫人是否可用 if( $(this).attr("isUserExist")=="yes"){ return false; } //首先判斷輸入的參數是否知足規則 if(!validate_add_form()){ return false; } $.ajax({ url:"${APP_PATH}/save", data:$("#addEmpModal form").serialize(), type:"post", success:function(result){ //首先須要判斷後端返回的結果中,後端對用戶的校驗結果 //alert(result.extend.err_map.email); //alert(result.extend.err_map.empName); //這裏須要注意的是若是郵箱格式錯誤,姓名正確,result.extend.err_map.email中就像攜帶錯誤的信息,result.extend.err_map.empName的信息是undefined if(result.code == 100){ //保存聯繫人成功須要作下面的幾件事情 //第一件事情就是讓新建聯繫人的對話框摸太框消失 $("#addEmpModal").modal('hide'); //第二個跳轉到最後一頁 //這裏如何跳轉到最後一頁了,mybatis分頁插件這裏提供了一個功能,例如如今員工總數是100人,每頁顯示5人,最大的分頁數目就是5,你若是輸入6 //也是按照最大的5來進行查詢。員工的總數確定是大於最大的分頁數目的,如今要查詢最後一頁的數據,我以員工的總數進行查詢 //使用ajax從新再查詢下最後一頁員工的數目 // to_page(total); }else{ alert(result.extend.err_map.email); //說明郵箱格式錯誤 if(undefined != result.extend.err_map.email){ alert(result.extend.err_map.email); $("#emailModal").parent().removeClass("has-success has-error"); $("#email_span").text(""); $("#emailModal").parent().addClass("has-error"); //給span節點添加.help-block屬性 $("#email_span").addClass("help-block").text(result.extend.err_map.email); } //說明姓名格式有錯誤 if(undefined != result.extend.err_map.empName){ //添加元素狀態以前。先清空清除當前元素的校驗狀態 $("#empNameModal").parent().removeClass("has-success has-error"); $("#name_span").text(""); //給當前節點的父元素添加has-error屬性 $("#empNameModal").parent().addClass("has-error"); //給span節點添加.help-block屬性 $("#name_span").addClass("help-block").text(result.extend.err_map.empName); } } } }); }); //juqery前臺校驗數據 //校驗表單數據 function validate_add_form(){ //一、拿到要校驗的數據,使用正則表達式 var empName = $("#empNameModal").val(); var regName = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u2E80-\u9FFF]{2,5})/; if(!regName.test(empName)){ //添加元素狀態以前。先清空清除當前元素的校驗狀態 $("#empNameModal").parent().removeClass("has-success has-error"); $("#name_span").text(""); //給當前節點的父元素添加has-error屬性 $("#empNameModal").parent().addClass("has-error"); //給span節點添加.help-block屬性 $("#name_span").addClass("help-block").text("姓名格式不正確"); return false; }else{ $("#empNameModal").parent().removeClass("has-success has-error"); $("#name_span").text(""); //給當前節點的父元素添加has-error屬性 $("#empNameModal").parent().addClass("has-success"); //給span節點添加.help-block屬性 $("#name_span").addClass("help-block").text(""); }; //二、校驗郵箱信息 var email = $("#emailModal").val(); var regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/; if(!regEmail.test(email)){ $("#emailModal").parent().removeClass("has-success has-error"); $("#email_span").text(""); $("#emailModal").parent().addClass("has-error"); //給span節點添加.help-block屬性 $("#email_span").addClass("help-block").text("郵箱格式不正確"); return false; }else{ $("#emailModal").parent().removeClass("has-success has-error"); $("#email_span").text(""); $("#emailModal").parent().addClass("has-success"); //給span節點添加.help-block屬性 $("#email_span").addClass("help-block").text(""); } return true; } //給輸入聯繫人的input添加change事件,判斷當前聯繫人是否可用 $("#empNameModal").change(function(){ //this表示當前操做的對象,是docment類型 //得到當前輸入的name的值 var name=$(this).val(); $.ajax({ url:"${APP_PATH}/isUserExist", type:"post", data:"empName="+name, success:function(result){ if(result.code == 200){ //說明該聯繫人已經在後臺存在不能夠 //添加元素狀態以前。先清空清除當前元素的校驗狀態 $("#empNameModal").parent().removeClass("has-success has-error"); $("#name_span").text(""); //給當前節點的父元素添加has-error屬性 $("#empNameModal").parent().addClass("has-error"); //給span節點添加.help-block屬性 $("#name_span").addClass("help-block").text("該聯繫人已經存在"); //若是當前聯繫人已經存在,點擊保存聯繫人案例的時候,就會失敗,咱們給保存聯繫人的按鈕添加一個自定義屬性用來標識當前添加的聯繫人是否存在 $("#saveEmp").attr("isUserExist","yes"); }else{ //說明該聯繫人可用 $("#empNameModal").parent().removeClass("has-success has-error"); $("#name_span").text(""); //給當前節點的父元素添加has-error屬性 $("#empNameModal").parent().addClass("has-success"); //給span節點添加.help-block屬性 $("#name_span").addClass("help-block").text("該聯繫人可用"); $("#saveEmp").attr("isUserExist","no"); } } }); }); </script> </div> </body> </html>
spring_mvc的配置文件爲
dispatcher-servlet.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"> <!-- 配置掃描控制器 ,springmvc值掃描controler,其餘的對象都讓spring去管理,這裏use-default-filters="false"要設置成false--> <context:component-scan base-package="com.atguigu" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 配置視圖解析器 --> <!-- 配置視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 配置視圖解析器的前綴和後綴 --> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean> <!-- 配置容許訪問靜態資源文件 --> <mvc:default-servlet-handler/> <!-- 支持springmvc的更加高級的東西 --> <mvc:annotation-driven></mvc:annotation-driven> </beans>
這樣須要注意一點的是:在tomcat服務器上運行的時候,jrs3030不支持tomact7如下的版本
咱們發佈的時候要選擇tomact7,不然你跑的時候發現驗證功能沒有效果
整個項目代碼的下載地址爲連接:https://pan.baidu.com/s/13ny24LsK1UBASgduHo4uBQ 密碼:pj2o