我的数据库设计是一张老师表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="更新学生信息信息" style="width: 400px; height: 450px;" data-options="modal:true"> <form id="upStu" method="post"> //id默认隐藏,这样就不允许修改 <div style="margin-bottom: 20px;"> <span>id</span> <input class="easyui-textbox" name="sid" id="sid" style="width: 200px;display: none;"> </div> <div style="margin-bottom: 20px"> <span>学生姓名</span> <input class="easyui-textbox" name="sname" style="width: 200px"> </div> <div style="margin-bottom: 20px"> <span>学生年龄</span> <input class="easyui-textbox" name="sage" style="width: 200px"> </div> </form> <div style="text-align: center; padding: 5px 0;"> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="updataForm()" style="width: 80px" id="tt">提交</a> </div> </div> <!-- 配置增加框 --> <div id="addStu" class="easyui-dialog" title="添加学生信息信息" style="width: 400px; height: 450px;" data-options="modal:true"> <form id="addStuf" method="post"> <!-- <div style="margin-bottom: 20px;display: none;"> <span>学生ID</span> <input class="easyui-textbox" name="sid" style="width: 200px;"> </div> --> <div style="margin-bottom: 20px"> <span>学生姓名</span> <input class="easyui-textbox" name="sname" style="width: 200px"> </div> <div style="margin-bottom: 20px"> <span> 学生年龄</span> <input class="easyui-textbox" name="sage"> </div> </form> <div style="text-align: center; padding: 5px 0;"> <a href="javascript:void(0)" class="easyui-linkbutton" onclick="addForm()" style="width: 80px" 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);