我的數據庫設計是一張老師表teacher,一張學生表student,一個教師對應多個學生,在學生一方建立外鍵;
還有一點想清楚,需要展示的數據是根據什麼來的,是成功登陸的用戶的id?還是直接展示所有的學生?
student表
教師表:
我是習慣性的從後寫到前,這裡展示的是登錄成功的老師下的學生信息
1 建立項目,建立好對應的包以及工具包
2建立好與數據庫對應的實體類
package com.zr.model; public class Student { private int sid; private String sname; private String sage; //自行get set public Student() { super(); } public Student(int sid, String sname, String sage) { super(); this.sid = sid; this.sname = sname; this.sage = sage; } }
package com.zr.model; public class Teacher { private int tid; private String tname; private String tpsw; //自行get set public Teacher(String tname, String tpsw) { super(); this.tname = tname; this.tpsw = tpsw; } public Teacher(int tid, String tname, String tpsw) { super(); this.tid = tid; this.tname = tname; this.tpsw = tpsw; } public Teacher() { super(); } }
3 StudentDao.java,因為使用的是easyUI,所以傳入參數多了起始頁碼start和頁面容量pageSize,這兩個參數都是從頁面的datagrid獲取的,是datagrid自帶的參數,方便後面的分頁
package com.zr.dao; import java.util.List; import com.zr.model.Student; public interface StudentDao { /** * * @param tid * @return 學生對象 * 根據老師id返回學生對象 */ public List<Student> getStudentBytid(int tid,int start,int pageSize); /** * 根據學生id刪除學生 * @param s * @return */ public boolean deleteStudentsBysid(String s[]); /** * 根據學生id更新學生信息 * @param student * @return */ public boolean updateStudentBysid(int sid, String sname,String sage); /** * 根據當前老師id添加學生 */ public boolean addStudent(String sname,String sage,int tid);
/** * @param tid傳入老師ID * @return 返回學生總數 */ public int getScountStudentByTid(int tid);
}
4 StudentDaoImpl.java實現studentDao.java
package com.zr.daoIm; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import JDBCUtil.JDBCUtil; import com.zr.dao.StudentDao; import com.zr.model.Student; public class StudentDaoImpl implements StudentDao{ /** * 根據傳入的老師id獲取學生 */ public List<Student> getStudentBytid(int tid,int start,int pageSize) { //定義學生對象集合students接收數據庫返回 List<Student> students = new ArrayList<Student>(); //獲取數據庫連接 Connection con=JDBCUtil.getConnection(); //編寫SQL語句 StringBuffer sql=new StringBuffer("select sid,sname,sage from student where tid=? limit ?,?"); try { PreparedStatement pst=con.prepareStatement(sql.toString()); pst.setInt(1, tid); pst.setInt(2, start); pst.setInt(3, pageSize); //返回一個結果集 ResultSet rs=pst.executeQuery(); while (rs.next()) { //學生對象接收結果集的結果 Student s=new Student(); s.setSid(rs.getInt("sid")); s.setSname(rs.getString("sname")); s.setSage(rs.getString("sage")); students.add(s); } } catch (SQLException e) { e.printStackTrace(); } return students; }
@Override public int getScountStudentByTid(int tid) { int scounts=0; StringBuffer sql=new StringBuffer("select count(sid) scount from student where tid=?"); Connection con=JDBCUtil.getConnection(); try { PreparedStatement pst=con.prepareStatement(sql.toString()); pst.setInt(1, tid); ResultSet rs=pst.executeQuery(); while(rs.next()){ scounts=rs.getInt("scount"); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return scounts; }
}
5 service層:searchService.java以及實現層searchServiceImpl.java
package com.zr.service; import java.util.List; import com.zr.model.Student; public interface searchService { /** * 查詢服務 * @param tid 通過老師ID * @return 學生對象所有信息 */ public List<Student> getStudents(int tid,int start,int pageSize);
/** * * @param tid傳入老師ID * @return 返回學生總數 */ public int getScountStudentByTid(int tid);
}
package com.zr.serviceIm; import java.util.ArrayList; import java.util.List; import com.zr.dao.StudentDao; import com.zr.dao.TeacherDao; import com.zr.daoIm.StudentDaoImpl; import com.zr.daoIm.TeacherDaoImpl; import com.zr.model.Student; import com.zr.service.searchService; public class searchServiceImpl implements searchService{ public List<Student> getStudents(int tid,int start,int pageSize) { List<Student> students=new ArrayList<Student>(); StudentDao studentDaoImpl =new StudentDaoImpl(); students= studentDaoImpl.getStudentBytid(tid,start,pageSize); return students; }
@Override public int getScountStudentByTid(int tid) { TeacherDao teacherDao =new TeacherDaoImpl(); return teacherDao.getScountStudentByTid(tid); }
}
6 控制層com.zr.controller.SearchController.java
注:控制層涉及一個參數scount是當前老師下的學生總數
import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.zr.model.Student; import com.zr.model.Teacher; import com.zr.service.searchService; import com.zr.serviceIm.searchServiceImpl; import net.sf.json.JSONArray; import net.sf.json.JSONObject; public class SearchController extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //設置字符編碼 req.setCharacterEncoding("utf8"); resp.setCharacterEncoding("utf8"); //實例化服務層,方便參數調用 searchService s=new searchServiceImpl(); //獲取datagrid的分頁參數page當前頁碼和頁面容量rows,保持參數名一直 int page=Integer.parseInt(req.getParameter("page")); int rows=Integer.parseInt(req.getParameter("rows")); //用學生集合接收返回的數據 List<Student> students=new ArrayList<Student>(); //起始頁碼start=當前頁碼減1乘以頁面容量 int start= (page-1)*rows; //獲取存放在session中的teacher對象,在登錄的時候返回老師對象並存入session對象 Teacher teacher=(Teacher) req.getSession().getAttribute("teacher"); //獲取老師ID int tid= teacher.getTid();
int scount =s.getScountStudentByTid(tid); //根據老師id獲取學生對象 students= s.getStudents(tid, start, rows); //easy前台接收的是json對象JSONObject JSONObject jso=new JSONObject(); //將數據返回給datagrid jso.put("total",scount); //rows後邊的參數代表需要在前台顯示的數據,格式為json的集合,再放入json的對象中 jso.put("rows", JSONArray.fromObject(students)); jso.put("page", start); resp.getWriter().write(jso.toString()); } }
7 前台頁面編寫main.jsp
數據展示並不需要進行過多的配置,只需要配置好對應的列名以及請求參數,數據格式,本頁面前台的配置包含整個數據的增加,刪除,修改
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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"> <link href="${pageContext.request.contextPath}/themes/bootstrap/easyui.css" rel="stylesheet"> <link href="${pageContext.request.contextPath}/themes/icon.css" rel="stylesheet"> <script src="${pageContext.request.contextPath}/js/jquery.min.js"></script> <script src="${pageContext.request.contextPath}/js/jquery.easyui.min.js"></script> <script src="${pageContext.request.contextPath}/js/easyui-lang-zh_CN.js"></script> <title>login</title> <script type="text/javascript"> $(function(){ //將增加框和修改框進行隱藏
$('#updateStu').dialog('close'); $('#addStu').dialog('close'); //配置學生信息表格 $('#students').datagrid({ url:'${pageContext.request.contextPath}/selectStus', columns:[[ {field:'checked',checkbox:true,width:100}, {field:'sid',title:'ID',width:100}, {field:'sname',title:'姓名',width:100}, {field:'sage',title:'年齡',width:100,align:'right'} ]], pagination : true, //顯示分頁 pagePosition:'bottom',//分頁顯示在底部 toolbar: [{ iconCls: 'icon-edit', text:'添加', handler: function(){ $('#addStu').dialog('open');//點擊添加按鈕顯示添加框 } },'-',{ iconCls: 'icon-delete', text:'刪除', handler: function(){ var sids=''; var ss=$("#students").datagrid('getSelections');//接收選中的對象結果集
if(ss.length==0){//對選中的大小判斷 $.messager.alert('這是一個提示信息!','請至少選擇一條數據進行刪除!'); }else{
//對選中數據的id以逗號進行拼接,結果會多一個逗號,後台再進行處理:截取字符串 $.messager.confirm('提示', '確認刪除?', function(r) { $.each(ss,function(n,v){ sids=sids+v.sid+',' }); $.ajax({ type:'post', url:'${pageContext.request.contextPath}/deleteStus', data:{'sids':sids}, dataType:"text", success:function(data){ if(data=="1"){ $.messager.alert('提示','刪除成功!'); $("#students").datagrid('reload'); }else{ $.messager.confirm('刪除失敗!',"刪除數據失敗!"); } } }) }); } } },'-',{ iconCls: 'icon-update', text:'修改', handler: function(){ var stus = $("#students").datagrid('getSelections'); if (stus.length != 1) { $.messager.confirm('提示', '請選擇一條數據', function(r){ $("#students").datagrid('unselectAll'); }) } else { //顯示修改框 $('#updateStu').dialog('open');
//將選中的數據加載到修改面板上
var stu = stus[0]; $('#upStu').form('load',stu); } } }] }); /* 配置添加框 */ $("#addStuf").form({ type:'post', url:'${pageContext.request.contextPath}/AddStu', dataType:"text", success : function(data) { if(data=="1"){ $('#addStu').dialog('close'); $('#addStuf').form('clear'); $.messager.alert('我的消息','添加商品信息成功','info',function(){ $('#students').datagrid('reload'); }); }else{ $.messager.alert('我的消息','添加商品信息失敗,重新添加','info',function(){ $("#addStuf").form('clear'); }); } } }); /* 配置修改框 */ $("#upStu").form({ type:'post', url:'${pageContext.request.contextPath}/updataStu', dataType:"text", success : function(data) { if(data=="1"){ $("#students").datagrid('reload'); $.messager.alert('提示!','修改成功'); $('#updateStu').dialog('close'); }else{ $.messager.alert('我的消息','修改學生信息失敗!','修改失敗!',function(){ $('#upStu').form('clear'); }); } } }); <!--配置搜索框,該功能尚未實現--> $('#searchStu').searchbox({ searcher : function(value, name) { var sname = value; $('#goods').datagrid('reload', { searchname : sname, }); } }); }); //配置修改學生信息表單提交 function updataForm() { $("#upStu").form('submit'); }
function addForm() { $("#addStuf").form('submit'); } </script> </head> <body> <input id="searchStu" class="easyui-searchbox" data-options="prompt:'輸入學生查詢信息',width:150"> <table id="students"></table> <!-- 配置修改框面板 --> <div id="updateStu" class="easyui-dialog" title="更新學生信息信息" data-options="modal:true"> <form id="upStu" method="post"> //id默認隱藏,這樣就不允許修改 <div > <span>id</span> <input class="easyui-textbox" name="sid" id="sid" > </div> <div > <span>學生姓名</span> <input class="easyui-textbox" name="sname" > </div> <div > <span>學生年齡</span> <input class="easyui-textbox" name="sage" > </div> </form> <div > <a href="javascript:void(0)" class="easyui-linkbutton" onclick="updataForm()" id="tt">提交</a> </div> </div> <!-- 配置增加框 --> <div id="addStu" class="easyui-dialog" title="添加學生信息信息" data-options="modal:true"> <form id="addStuf" method="post"> <!-- <div>--> <div > <span>學生姓名</span> <input class="easyui-textbox" name="sname" > </div> <div > <span> 學生年齡</span> <input class="easyui-textbox" name="sage"> </div> </form> <div > <a href="javascript:void(0)" class="easyui-linkbutton" onclick="addForm()" id="tt">提交</a> </div> </div> </body> </html>
最後配置請求文件
<!-- 查詢當前下面的學生信息 --> <servlet> <servlet-name>selectStus</servlet-name> <servlet-class>com.zr.controller.SearchController</servlet-class> </servlet> <servlet-mapping> <servlet-name>selectStus</servlet-name> <url-pattern>/selectStus</url-pattern> </servlet-mapping>
最後數據展示:
總結:利用easyUI進行數據展示的時候,自帶的參數page,rows是需要獲取的,並以此來實現分頁功能;
後台返回到前台的時候,需要返回三個參數:
page: int page=Integer.parseInt(req.getParameter("page")); int start= (page-1)*rows; jso.put("page", start);
rows是需要展示的數據json集合 jso.put("rows", JSONArray.fromObject(students));
第三個需要返回的是數據總數total:jso.put("total",scount);