數據庫配置文件application-context-jdbc.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:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd "> <!--配置mysql數據庫--> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName"> <value>com.mysql.jdbc.Driver</value> </property> <property name="url"> <value>jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=UTF-8</value> </property> <property name="username"> <value>root</value> </property> <property name="password"> <value>root</value> </property> </bean> <!--jdbcTemplate和數據庫關聯--> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name = "dataSource" ref="dataSource"/> </bean> </beans>
表teacher的結構(tid自增,tno工號,tname姓名,dno部門號)
tid int auto_increment primary key,tno varchar(20),tname varchar(20),dno varchar(10)
分頁類PageResult
package com.zyz.dao.base; /** * Created by zyz on 2016-8-11. */ import java.io.Serializable; import java.util.List; import org.springframework.jdbc.core.JdbcTemplate; public class PageResult<T> implements Serializable { public static final int NUMBERS_PER_PAGE = 10;//默認每頁10條記錄 //每頁顯示的記錄數 private int numPerPage; //記錄總數 private int totalRows; //總頁數 private int totalPages; //當前頁碼 private int currentPage; //起始行數 private int startIndex; //結束行數 private int lastIndex; //結果集存放List private List<T> resultList; //JdbcTemplate jTemplate private JdbcTemplate jdbcTemplate; /** * 每頁顯示10條記錄的構造函數,使用該函數必須先給Pagination設置currentPage,jTemplate初值 * @param sql oracle語句 */ public PageResult(String sql){ if(jdbcTemplate == null){ throw new IllegalArgumentException("com.itbegin.dao.base.PageResult.jTemplate is null,please initial it first. "); }else if(sql.equals("")){ throw new IllegalArgumentException("com.itbegin.dao.base.PageResult.sql is empty,please initial it first. "); } new PageResult<T>(sql,currentPage,NUMBERS_PER_PAGE,jdbcTemplate); } /**分頁構造函數 * @param sql 根據傳入的sql語句得到一些基本分頁信息 * @param currentPage 當前頁 * @param numPerPage 每頁記錄數 * @param jTemplate JdbcTemplate實例 */ public PageResult(String sql,int currentPage,int numPerPage,JdbcTemplate jTemplate){ if(jTemplate == null){ throw new IllegalArgumentException("com.deity.ranking.util.Pagination.jTemplate is null,please initial it first. "); }else if(sql == null || sql.equals("")){ throw new IllegalArgumentException("com.deity.ranking.util.Pagination.sql is empty,please initial it first. "); } //設置每頁顯示記錄數 setNumPerPage(numPerPage); //設置要顯示的頁數 setCurrentPage(currentPage); //計算總記錄數 StringBuffer totalSQL = new StringBuffer(" SELECT count(*) FROM ( "); totalSQL.append(sql); totalSQL.append(" ) totalTable "); //給JdbcTemplate賦值 this.jdbcTemplate = jTemplate; //總記錄數 setTotalRows(getJdbcTemplate().queryForObject(totalSQL.toString(),Integer.class)); //計算總頁數 setTotalPages(); //計算起始行數 setStartIndex(); //計算結束行數 setLastIndex(); //裝入結果集 setResultList(getJdbcTemplate().queryForList(getMySQLPageSQL(sql,startIndex,numPerPage))); } /** * 構造MySQL數據分頁SQL * @param queryString * @param startIndex * @param pageSize * @return */ public String getMySQLPageSQL(String queryString, Integer startIndex, Integer pageSize) { String result = ""; if (null != startIndex && null != pageSize) { result = queryString + " limit " + startIndex + "," + pageSize; } else if (null != startIndex && null == pageSize) { result = queryString + " limit " + startIndex; } else { result = queryString; } return result; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getNumPerPage() { return numPerPage; } public void setNumPerPage(int numPerPage) { this.numPerPage = numPerPage; } public List<T> getResultList() { return resultList; } public void setResultList(List resultList) { this.resultList = resultList; } public int getTotalPages() { return totalPages; } //計算總頁數 public void setTotalPages() { if(totalRows % numPerPage == 0){ this.totalPages = totalRows / numPerPage; }else{ this.totalPages = (totalRows / numPerPage) + 1; } } public int getTotalRows() { return totalRows; } public void setTotalRows(int totalRows) { this.totalRows = totalRows; } public int getStartIndex() { return startIndex; } public void setStartIndex() { this.startIndex = (currentPage - 1) * numPerPage; } public int getLastIndex() { return lastIndex; } public JdbcTemplate getJdbcTemplate() { return jdbcTemplate; } public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } //計算結束時候的索引 public void setLastIndex() { //System.out.println("totalRows="+totalRows);/////////// //System.out.println("numPerPage="+numPerPage);/////////// if( totalRows < numPerPage){ this.lastIndex = totalRows; }else if((totalRows % numPerPage == 0) || (totalRows % numPerPage != 0 && currentPage < totalPages)){ this.lastIndex = currentPage * numPerPage; }else if(totalRows % numPerPage != 0 && currentPage == totalPages){//最后一頁 this.lastIndex = totalRows ; } } @Override public String toString() { return "totalRows:"+totalRows+" totalPages:"+totalPages+" currentPage:"+currentPage+resultList; } }
實體類Model
package com.zyz.model; /** * Created by zyz on 2016-8-3. */ public class Teacher { private int tid; private String tno; private String tname; private String dno; public int getTid() { return tid; } public void setTid(int tid) { this.tid = tid; } public String getTno() { return tno; } public void setTno(String tno) { this.tno = tno; } public String getTname() { return tname; } public void setTname(String tname) { this.tname = tname; } public String getDno() { return dno; } public void setDno(String dno) { this.dno = dno; } }
數據訪問層DAO-TeacherDao
package com.zyz.dao; import com.zyz.dao.base.PageResult; import com.zyz.model.Teacher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.PreparedStatementSetter; import org.springframework.stereotype.Repository; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Created by zyz on 2016-8-3. */ @Repository public class TeacherDao { @Autowired private JdbcTemplate jdbcTemplate; public PageResult<Teacher> queryPage(Integer currentPage,Integer numPerPage,Teacher teacher){ StringBuffer sql=new StringBuffer(); sql.append("select tid, tno,tname,dno from teacher where 1=1 "); if(teacher!=null){ if(teacher.getTname()!=null && !teacher.getTname().equals("")){ sql.append(" and tname like '"); sql.append(teacher.getTname()); sql.append("%' "); } if(teacher.getDno()!=null && !teacher.getDno().equals("")){ sql.append(" and dno like '"); sql.append(teacher.getDno()); sql.append("%' "); } } sql.append(" order by tno asc"); PageResult<Teacher> page=new PageResult<Teacher>(sql.toString(),currentPage,numPerPage,this.jdbcTemplate); return page; } public List<Teacher> getTeachers(){ List<Teacher> teachers=new ArrayList<Teacher>(); String sql="select tid, tno,tname,dno from teacher"; teachers=jdbcTemplate.query(sql,new BeanPropertyRowMapper<Teacher>(Teacher.class)); return teachers; } public void addTeacher(Teacher teacher){ String sql="insert into teacher(tno,tname,dno) values(?,?,?)"; jdbcTemplate.update(sql, new PreparedStatementSetter() { @Override public void setValues(PreparedStatement ps) throws SQLException { ps.setString(1,teacher.getTno()); ps.setString(2,teacher.getTname()); ps.setString(3,teacher.getDno()); } }); } public Teacher getTeacher(int tid){ String sql="select tid,tno,tname,dno from teacher where tid=?"; Teacher teacher=jdbcTemplate.queryForObject(sql,new Object[]{tid},new BeanPropertyRowMapper<Teacher>(Teacher.class)); return teacher; } public void update(Teacher teacher){ String sql="update teacher set tno=?,tname=?,dno=? where tid=?"; jdbcTemplate.update(sql,new Object[]{teacher.getTno(),teacher.getTname(),teacher.getDno(),teacher.getTid()}); } public void delete(int tid){ String sql="delete from teacher where tid=?"; jdbcTemplate.update(sql,new Object[]{tid}); } }
業務邏輯層Service-TeacherService
package com.zyz.service; import com.zyz.dao.TeacherDao; import com.zyz.dao.base.PageResult; import com.zyz.model.Teacher; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by zyz on 2016-8-3. */ @Service public class TeacherService { @Autowired private TeacherDao teacherDao; public PageResult<Teacher> queryPageBusiness(Integer currentPage,Integer numPerPage,Teacher teacher){ return teacherDao.queryPage(currentPage,numPerPage,teacher); } public List<Teacher> getTeachers(){ return teacherDao.getTeachers(); } public void addTeacher(Teacher teacher){ teacherDao.addTeacher(teacher); } public Teacher getTeacher(int tid){ return teacherDao.getTeacher(tid);} public void update(Teacher teacher){teacherDao.update(teacher);} public void delete(int tid){teacherDao.delete(tid);} }
控制層Controller-TeacherController
package com.zyz.action; import com.zyz.api.Msg; import com.zyz.dao.base.PageResult; import com.zyz.model.Teacher; import com.zyz.service.TeacherService; import com.zyz.util.StrUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import java.util.HashMap; import java.util.Map; /** * Created by zyz on 2016-8-3. */ @Controller @RequestMapping("/teacher") public class TeacherController { @Autowired private TeacherService teacherService; private static final int PAGE_LIMIT=3; @RequestMapping(value = "/list",method =RequestMethod.GET) public String teacherInfo(String page,Model model){ Integer currPage=1; if(page!=null && !page.equals("")){ currPage=new Integer(page); } PageResult<Teacher> pageResult=teacherService.queryPageBusiness(currPage,new Integer(PAGE_LIMIT),new Teacher()); model.addAttribute("pageUrl","/teacher/list?1=1"); model.addAttribute("teachers",pageResult); return "/teacher/list"; } @RequestMapping(value = "/find",method = RequestMethod.GET) public String teacherFind(String tname,String dno,String page,Model model){ Integer currPage = 1; if(page!=null && !page.equals("")){ currPage = new Integer(page); } Teacher teacher=new Teacher(); teacher.setTname(tname); teacher.setDno(dno); PageResult<Teacher> pageResult = teacherService.queryPageBusiness(currPage, new Integer(PAGE_LIMIT),teacher ); model.addAttribute("pageUrl", "/teacher/find?1=1&tname="+tname+"&dno="+dno); model.addAttribute("teachers", pageResult); model.addAttribute("findTeacher", teacher); return "/teacher/list"; } @RequestMapping(value = "/add",method = RequestMethod.GET) public String addTeacher(){ return "/teacher/add"; } @RequestMapping(value = "/edit/{id}",method = RequestMethod.GET) public String edit(@PathVariable String id,Model model){ try { int tid=Integer.valueOf(id); Teacher teacher=teacherService.getTeacher(tid); model.addAttribute("teacher",teacher); return "/teacher/edit"; }catch (NumberFormatException ex){ return "/teacher/list"; } } @RequestMapping(value = "/edit/save",method = RequestMethod.POST) public String update(@ModelAttribute("teacher") Teacher teacher, Model model){ Map<String,Msg> msgs=new HashMap<>(); if(StrUtil.isEmpty(teacher.getTno())){ msgs.put("tno",new Msg("tno","工號不能為空.")); } if(StrUtil.isEmpty(teacher.getTname())){ msgs.put("tname",new Msg("tname","姓名不能為空.")); } if(StrUtil.isEmpty(teacher.getDno())){ msgs.put("dno",new Msg("dno","部門不能為空.")); } try { if(msgs.isEmpty()){ teacherService.update(teacher); model.addAttribute("success",new Msg("","更新成功.")); } }catch (Exception ex){ model.addAttribute("error",new Msg("","更新失敗.")); } model.addAttribute("msgs",msgs); model.addAttribute("teacher",teacher); return "/teacher/edit"; } @RequestMapping(value = "/delete/{id}",method = RequestMethod.GET) public String delete(@PathVariable String id,Model model){ try { int tid=Integer.valueOf(id); teacherService.delete(tid); model.addAttribute("success",new Msg("","刪除成功.")); }catch (Exception ex){ model.addAttribute("error",new Msg("","刪除失敗:"+ex.getMessage())); } return teacherInfo("",model); } }
數據檢驗-TeacherApi
package com.zyz.api; import com.zyz.model.Teacher; import com.zyz.service.TeacherService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.List; /** * Created by zyz on 2016-8-4. */ @RestController @RequestMapping("/teacher") public class TeacherApi { @Autowired private TeacherService teacherService; @RequestMapping(value = "/add",method = RequestMethod.POST) public ResponseData add(@RequestBody Teacher teacher){ List<Msg> msgs=new ArrayList<Msg>(); if(teacher.getTno()==null || teacher.getTno().equals("")){ msgs.add(new Msg("tnoMsg","工號不能為空.")); } if(teacher.getTname()==null || teacher.getTname().equals("")){ msgs.add(new Msg("tnameMsg","姓名不能為空.")); } if(teacher.getDno()==null || teacher.getDno().equals("")){ msgs.add(new Msg("dnoMsg","部門號不能為空.")); } if(msgs.size()==0){ teacherService.addTeacher(teacher); return new ResponseData(true,"添加成功."); }else { return new ResponseData(false,"添加失敗.",msgs); } } }
分頁定自義標簽-pager.ftl
<#macro pager url totalPage curPage=1 showPageNum=4> <#if (totalPage?number > 1)> <div class="holder"> <nav class="center"> <ul class="pagination" pages="${totalPage}" id="ul"> <li id="Previous" <#if curPage?number == 1>class="disabled"</#if>> <a href="${url}?page=1" aria-label="Previous"> <span aria-hidden="true">«</span> </a> </li> <@pagercount url=url totalPage=totalPage curPage=curPage showPageNum=showPageNum/> <li id="Next" <#if curPage?number==totalPage?number>class="disabled"</#if>><a href="${url}?page=${totalPage}" aria-label="Next"> <span aria-hidden="true">»</span> </a></li> </ul> </nav> </div> </#if> </#macro> <#macro pagercount url totalPage curPage showPageNum> <#local halfPage =(showPageNum/2)?int/> <#local curPage = curPage?number/> <#if (halfPage>=curPage)> <@showPage start=1 end=curPage curPage=curPage url=url /> <#if (showPageNum > (totalPage?number))> <@showPage start=curPage+1 end=(totalPage?number) curPage=curPage url=url/> <#else> <@showPage start=curPage+1 end=showPageNum curPage=curPage url=url/> </#if> <#else> <#local startPage1 = (curPage-halfPage) /> <#local startPage2 = curPage+1 /> <#if ((curPage+halfPage)>(totalPage?number))> <#local endPage = (totalPage?number)/> <#if (showPageNum > (endPage-startPage1)+1)> <#local startPage1 = (curPage-halfPage)-1 /> <#if startPage1 <= 0> <#local startPage1 = (curPage-halfPage) /> </#if> </#if> <#else> <#local endPage = curPage + halfPage/> <#if ((endPage-startPage1) >= showPageNum)> <#local startPage1 = startPage1+1 /> </#if> </#if> <@showPage start=startPage1 end=curPage curPage=curPage url=url /> <@showPage start=startPage2 end=endPage url=url curPage=curPage/> </#if> </#macro> <#macro showPage start end curPage url> <#if (end >= start) > <#list start..end as page> <li id="${(page)}" <#if curPage==page>class="active"</#if> > <a href="${url}&page=${page}" class="btn btn-default" role="button"><span>${(page)} <#if curPage==page> <span class="sr-only">(current)</span></span> </#if> </a> </li> </#list> </#if> </#macro>
查-list.ftl
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>教師列表</title> <link rel="stylesheet" href="/css/common/bootstrap.min.css"> <script src="/js/common/jquery.min.js"></script> <script src="/js/common/bootstrap.min.js"></script> <style> .msg{ color: #f00; } </style> </head> <body> <#include "../common/pager.ftl"> <h3 class="msg"> <#if success?exists>${success.msg!}</#if> <#if error?exists>${error.msg!}</#if> </h3> <div> 姓名:<input type="text" id="tname" name="tname" value="<#if (findTeacher.tname)??>${findTeacher.tname!}</#if>" > 部門號:<input type="text" id="dno" name="dno" value="<#if (findTeacher.dno)??>${findTeacher.dno!}</#if>"> <input type="button" id="btnFind" value="查找" class="btn btn-primary"> <input type="button" id="btnAdd" value="新增" class="btn btn-primary" onclick="window.location.href='/teacher/add'"> <input type="button" id="btnModify" value="修改" class="btn btn-primary"> <input type="button" id="btnDelete" value="刪除" class="btn btn-primary"> </div> <table class="table table-bordered table-hover"> <tr> <th>#</th> <th>工號</th> <th>姓名</th> <th>部門號</th> </tr> <#list teachers.resultList as teacher> <tr> <td><input type="radio" name="teacher" value="${teacher.tid!}"></td> <td>${teacher.tno!}</td> <td>${teacher.tname!}</td> <td>${teacher.dno!}</td> </tr> </#list> </table> <nav> <!-- 顯示分頁 --> <#if teachers?exists> <@pager url='${pageUrl}' totalPage='${teachers.getTotalPages()}' curPage='${teachers.getCurrentPage()}'/> </#if> </nav> <script src="/js/teacher/list.js"></script> </body> </html>
查-list.js
/** * Created by zyz on 2016-8-11. */ $(function () { $("#btnFind").on("click",function () { var url="/teacher/find?tname="+$("#tname").val()+"&dno="+$("#dno").val(); window.location.href=url; }); $("#btnModify").on("click",function () { var id=$("input[name='teacher']:checked").val(); if(id){ window.location.href="/teacher/edit/"+id; } }); $("#btnDelete").on("click",function () { var id=$("input[name='teacher']:checked").val(); if(id){ window.location.href="/teacher/delete/"+id; } }); })
增-add.ftl
<!doctype html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>添加教師</title> <style> .msg{ color:red; } </style> </head> <body> 工號:<input type="text" id="tno"><span id="tnoMsg" class="msg"></span><br> 姓名:<input type="text" id="tname"><span id="tnameMsg" class="msg"></span><br> 部門號:<input type="text" id="dno"><span id="dnoMsg" class="msg"></span><br> <input type="button" id="add" value="添加"> <script src="/js/common/jquery.min.js"></script> <script src="/js/teacher/add.js"></script> </body> </html>
增-add.js(Ajax提交)
/** * Created by zyz on 2016-8-2. */ $(function () { // 將所有class為msg的元素內容清空,這些元素通常提示錯誤信息的,每次提交前都要清除,以顯示本次的信息 function clearMsg() { $(".msg").html(''); } //獲取表單數據,返回一個json對象,准備提交給服務器,注意此處json對象的屬性必須和對應model對象Person的屬性名保持一致 function formData() { return { tno:$("#tno").val(), tname:$("#tname").val(), dno:$("#dno").val() }; } function add() { var url="/teacher/add";//通過該url找到對應api類的某個方法來接收ajax請求並作出響應(返回一個json對象) var data=formData();//此處的data是一個json對象 clearMsg(); $.ajax({ type:'POST',//處理異步請求數據的api類@RequestMapping(value="/add",method=RequestMethod.POST) url: url, dataType:'json', contentType: 'application/json', data:JSON.stringify(data), //將一個json對象轉換成json對象字符串,因為在api中參數@RequestBody接受的是一個json對象字符串,而不是一個json對象 success:function (responseData) {//此處success是表示響應成功,即狀態碼為200,responseData參數表示返回的數據 if(responseData.success==true){ //ResponseData是一個json對象,是由后台類(ResponseData(success,desc,msgs)類)的對象返回到前台形成的一個json對象, // 此處的success僅表示該json對象的一個屬性, alert(responseData.desc); window.location.href="/teacher/list"; }else {//如果驗證失敗,則 顯示錯誤信息 var msgs=responseData.msgs; for(var i=0;i<msgs.length;i++){ $('#'+msgs[i].id).html(msgs[i].msg); } } } }); } // 定義一個初始化的方法 function init() { $("#add").on("click",function () {//給添加按紐綁定事件 add(); }); } init();//調用初始化事件 })
改-edit.ftl
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>修改</title> <link rel="stylesheet" href="/css/common/bootstrap.min.css"> <script src="/js/common/jquery.min.js"></script> <script src="/js/common/bootstrap.min.js"></script> <style> .msg{ color: #f00; } </style> </head> <body> <form action="/teacher/edit/save" method="post"> <input type="hidden" name="tid" value="${teacher.tid!}"> <#if success?exists > <h3 class="msg">${success.msg!}</h3> </#if> <#if error?exists > <h3 class="msg">${error.msg!}</h3> </#if> 工號:<input type="text" name="tno" value="${teacher.tno!}"> <#if msgs?exists> <#if msgs["tno"]?exists> <span class="msg">${msgs["tno"].msg!}</span> </#if> </#if> <br> 姓名:<input type="text" name="tname" value="${teacher.tname!}"> <#if msgs?exists> <#if msgs["tname"]?exists> <span class="msg">${msgs["tname"].msg!}</span> </#if> </#if> <br> 部門:<input type="text" name="dno" value="${teacher.dno!}"> <#if msgs?exists> <#if msgs["dno"]?exists> <span class="msg">${msgs["dno"].msg!}</span> </#if> </#if> <br> <input type="submit" value="保存" class="btn btn-primary"> <input type="button" value="返回" class="btn btn-primary" onclick="window.location.href='/teacher/list'"> </form> </body> </html>