BaseDao
package day21; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import com.sun.org.apache.bcel.internal.generic.NEW; public abstract class BaseDao { public List findAllObject(Connection conn, String sqlList, Class clazz) throws SQLException { return this.findAllObjectByCondition(conn, sqlList, clazz, null); } public List findAllObjectByCondition(Connection conn, String sqlList, Class clazz, Object ... params) throws SQLException { QueryRunner query=new QueryRunner(); return (List)query.query(conn, sqlList, new BeanListHandler(clazz),params); } @SuppressWarnings("unchecked") public int getCount(Connection conn, String sql) throws SQLException { /****************/ ResultSetHandler resultSetHandler=new ResultSetHandler() { public Object handle(ResultSet rs) throws SQLException { int count=0; if(rs.next()){ count=rs.getInt(1); } return count; } }; /*************** */ int count=0; QueryRunner query=new QueryRunner(); count=(Integer)query.query(conn, sql, resultSetHandler); return count; } public int getCount(Connection conn, String sql, Object[] params) throws SQLException { ResultSetHandler resultSetHandler=new ResultSetHandler() { public Object handle(ResultSet rs) throws SQLException { int count=0; if(rs.next()){ count=rs.getInt(1); } return count; } }; /*************** */ int count=0; QueryRunner query=new QueryRunner(); count=(Integer)query.query(conn, sql, resultSetHandler,params); return count; } }
package day21; public class DaoFactory { //获取职业接口对象 public static DaoStudent getDaoStudent() { return new DaoStudentImpl(); } }
package day21; import java.util.List; public interface DaoStudent { /* * 查询所有的记录和总记录数 */ QueryResult<Student> findAllStudent(int beginIndex, int maxSize); /* * 通过条件查询员工信息 */ QueryResult<Student> findAllStudentByCondition(SearchStudent searchStudent, int beginIndex, int maxSize) throws Exception; }
package day21; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class DaoStudentImpl extends BaseDao implements DaoStudent { //private String sqlCount; @SuppressWarnings("unchecked") public QueryResult<Student> findAllStudent(int beginIndex, int maxSize) { //查询页面显示的数据 DBManager dbManager=null; Connection conn=null; dbManager=DBManager.getDbManager(); try { conn=dbManager.getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } QueryResult<Student> qr=null; qr=new QueryResult<Student>(); //组织页面显示的SQL String sqlList="select id,username,sex,major from employees order by id limit "+beginIndex+","+maxSize; String sqlCount="select count(*) from employees"; //设置封装数据的javaBean Class clazz=Student.class; //调用父类的方法查询 try { List<Student> list=super.findAllObject(conn,sqlList,clazz); qr.setList(list); int count=super.getCount(conn,sqlCount); qr.setCount(count); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ try { dbManager.closeResource(conn, null,null); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return qr; } public QueryResult<Student> findAllStudentByCondition( SearchStudent searchStudent, int beginIndex, int maxSize) throws Exception { DBManager dbManager=null; Connection conn=null; dbManager=DBManager.getDbManager(); try { conn=dbManager.getConnection(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } QueryResult<Student> qr=null; qr=new QueryResult<Student>(); //组织页面显示的SQL String sqlList="select id,username,sex,major from employees where 1=1 "; String sqlCount="select count(*) from employees where 1=1 "; //组织查询调节 StringBuffer sqlWhere=new StringBuffer(""); //定义保存参数的List List paramList=new ArrayList(); if(searchStudent.getCname()!=null&&!"".equals(searchStudent.getCname().trim())){ sqlWhere.append(" and cname like ?"); paramList.add("%"+searchStudent.getCname().trim()+"%"); } if(searchStudent.getMajor()!=null&&!"".equals(searchStudent.getMajor().trim())){ sqlWhere.append(" and major like ?"); paramList.add("%"+searchStudent.getMajor().trim()+"%"); } //形成最终的SqL sqlList=sqlList+sqlWhere.toString(); //设置排序 sqlList=sqlList+" order by id"; //设置查询记录数 sqlList=sqlList+" limit "+beginIndex+","+maxSize; sqlCount=sqlCount+sqlWhere.toString(); System.out.println("sqlList= "+sqlList); System.out.println("sqlCount= "+sqlCount); //设置?参数值 Object[]params=paramList.toArray(); Class clazz=Student.class; List<Student> list=super.findAllObjectByCondition(conn, sqlList, clazz, params); qr.setList(list); int count=super.getCount(conn, sqlCount ,params); qr.setCount(count); dbManager.closeResource(conn, null, null); return qr; } }
package day21; import java.sql.Connection; import java.sql.SQLException; import org.apache.commons.dbcp.BasicDataSource; import com.mysql.jdbc.ResultSet; import com.mysql.jdbc.Statement; public class DBManager { //静态的变量是所有对象共享的,只在类执行的时候加载一次(称为懒汉式的单例模式) private static DBManager dbManager=new DBManager(); private BasicDataSource bds=null; /* * 私有的外部程序不能创建DBManager的实例 */ private DBManager(){ System.out.println("private DBManager()***********"); bds=new BasicDataSource(); //设置用户名与密码 bds.setUsername("root"); bds.setPassword("123456"); //设置url bds.setUrl("jdbc:mysql://localhost:3306/test"); //设置驱动 bds.setDriverClassName("com.mysql.jdbc.Driver"); //设置初始化连接数 bds.setInitialSize(4); //设置最大连接数 bds.setMaxActive(10); //设置最大空闲数 bds.setMaxIdle(5); //设置最小空闲数 bds.setMinIdle(3); //设置最大等待时间,以毫秒为单位 bds.setMaxWait(5000); } /* * 外部的程序获取DBManager对象的方法 */ public static DBManager getDbManager() { System.out.println("public static DBManager getDbManager() ~~~~~~~~"); return dbManager; } /* * 获取连接 */ public Connection getConnection() throws SQLException { Connection conn=null; conn=bds.getConnection(); return conn; } /* * 关闭资源 */ public void closeResource(Connection conn,Statement stmt,ResultSet rs) throws SQLException { if(rs!=null){ rs.close(); } if(stmt!=null){ stmt.close(); } if(conn!=null){ conn.close(); } } }
package day21; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ListConditionServlet extends HttpServlet { public ListConditionServlet() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); request.setCharacterEncoding("UTF-8"); String path=""; System.out.println(request.getParameter("flag")); SearchStudent searchStudent=new SearchStudent(); //设置分页的默认参数 int curPage=1;//当前页 int maxSize=3;//每页显示最大数 //获取当前要显示的页数 String scurPage=request.getParameter("curPage"); if(scurPage!=null&&!"".equals(scurPage.trim())){ curPage=Integer.parseInt(scurPage.trim()); } //获取每页显示的最大记录数 String smaxSize=request.getParameter("maxSize"); if(smaxSize!=null&&!"".equals(smaxSize.trim())){ maxSize=Integer.parseInt(smaxSize.trim()); } String flag="search"; String sflag=request.getParameter("flag"); if(sflag!=null&&!"".equals(sflag.trim())){ flag=sflag.trim(); } System.out.println("flag= "+flag); //如果flag=search 则点击的是“搜索”和菜单“高级查询”获取的页面输入 if("search".equals(flag)){ String cname=request.getParameter("cname"); String major=request.getParameter("jobname"); searchStudent.setCname(cname); searchStudent.setMajor(major); } //如果flag=page 则点击的是“上页。。。。”则获取的值应是上次点击“搜索”时的值 if("page".equals(flag)){ System.out.println("flag= "+flag); String cname=request.getParameter("old_cname"); String major=request.getParameter("old_jobname"); searchStudent.setCname(cname); searchStudent.setMajor(major); } request.setAttribute("searchStudent", searchStudent); //计算开始索引 int beginIndex=(curPage-1)*maxSize; /*String cname=request.getParameter("cname"); String major=request.getParameter("jobname"); searchStudent.setCname(cname); searchStudent.setMajor(major);*/ DaoStudent daoStudent=DaoFactory.getDaoStudent(); QueryResult<Student> qr = null; try { qr = daoStudent.findAllStudentByCondition(searchStudent,beginIndex, maxSize); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } if(qr!=null&&qr.getList()!=null){ request.setAttribute("listStudent", qr.getList()); } //设置分页信息 PageBean pageBean=new PageBean(); pageBean.init(curPage, qr.getCount(), maxSize); request.setAttribute("pageBean", pageBean); path="/listCondition.jsp"; request.getRequestDispatcher(path).forward(request, response); } /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { // Put your code here } }
package day21; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ListServlet extends HttpServlet { /** * 分页: * **2种分页 * ***查询所有符合条件的数据到内存中,缺点:占用内存 * ***页面显示什么,就查询什么,缺点:频繁操作数据库 * 分页需要的数据 * 总记录数 当前页 总页数 上一页 下一页 每页显示条数 页面显示的数据(List中) * * 从数据库中查询的:总记录数、页面显示的数据(List中) * 计算的: 当前页 总页数 上一页 下一页 每页显示条数 */ public ListServlet() { super(); } public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); request.setCharacterEncoding("UTF-8"); String path=""; System.out.println(request.getParameter("flag")); //设置分页的默认参数 int curPage=1;//当前页 int maxSize=3;//每页显示最大数 //获取当前要显示的页数 String scurPage=request.getParameter("curPage"); if(scurPage!=null&&!"".equals(scurPage.trim())){ curPage=Integer.parseInt(scurPage.trim()); } //获取每页显示的最大记录数 String smaxSize=request.getParameter("maxSize"); if(smaxSize!=null&&!"".equals(smaxSize.trim())){ maxSize=Integer.parseInt(smaxSize.trim()); } //计算开始索引 int beginIndex=(curPage-1)*maxSize; //获取DaoStudent接口对象 DaoStudent daoStudent=DaoFactory.getDaoStudent(); QueryResult<Student> qr=daoStudent.findAllStudent(beginIndex,maxSize); //放置页面显示的数据到作用域中 request.setAttribute("studentList", qr.getList()); //设置分页信息 PageBean pageBean=new PageBean(); pageBean.init(curPage, qr.getCount(), maxSize); request.setAttribute("pageBean", pageBean); path="/list.jsp"; request.getRequestDispatcher(path).forward(request, response); } public void init() throws ServletException { // Put your code here } }
package day21; import com.sun.faces.lifecycle.UpdateModelValuesPhase; public class PageBean { private int maxSize;//每页最大记录数 private int recordCnt;//总记录数 private int curPage;//当前页 private int pageCnt;//总页数 private int prePage;//上一页 private int nextPage;//下页 //对外接口 public void init(int curPage,int recordCnt,int maxSize) { this.curPage=curPage; this.recordCnt=recordCnt; this.maxSize=maxSize; //计算总页数 this.pageCnt=this.recordCnt/this.maxSize+(this.recordCnt%this.maxSize==0?0:1); //计算上,下页 update(curPage); } public void update(int curPage) { //计算上页 if(curPage<=1){ this.prePage=1; }else{ this.prePage=curPage-1; } //计算下一页 if(curPage>=this.pageCnt){ this.nextPage=this.pageCnt; }else{ this.nextPage=curPage+1; } } public int getRecordCnt() { return recordCnt; } public void setRecordCnt(int recordCnt) { this.recordCnt = recordCnt; } public int getCurPage() { return curPage; } public void setCurPage(int curPage) { this.curPage = curPage; } public int getPageCnt() { return pageCnt; } public void setPageCnt(int pageCnt) { this.pageCnt = pageCnt; } public int getPrePage() { return prePage; } public void setPrePage(int prePage) { this.prePage = prePage; } public int getNextPage() { return nextPage; } public void setNextPage(int nextPage) { this.nextPage = nextPage; } public int getMaxSize() { return maxSize; } public void setMaxSize(int maxSize) { this.maxSize = maxSize; } }
package day21; import java.util.List; public class QueryResult<T>{ private List list;//页面显示的数据 private int count;//总的记录数 public List<Student> getList() { return list; } public void setList(List list) { this.list = list; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } }
package day21; public class SearchStudent { private String cname; private String jobname; private String major; public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } public String getJobname() { return jobname; } public void setJobname(String jobname) { this.jobname = jobname; } }
package day21; public class Student { private Integer id; private String username; private String major; private String sex; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
package day21; import org.junit.Ignore; import org.junit.Test; public class TestDaoStudent { @Ignore public void findAllStudent(){ DaoStudent daoStudent=DaoFactory.getDaoStudent(); /* * 模拟数据 */ int beginIndex=0; int maxSize=3; QueryResult <Student> qr=daoStudent.findAllStudent(beginIndex, maxSize); if(qr!=null&&qr.getList()!=null){ for(Student st:qr.getList()){ System.out.println(st.getId()+" "+st.getUsername()); } } System.out.println("总的记录数:"+qr.getCount()); //计算上页 下页 总页等信息 PageBean pageBean=new PageBean(); pageBean.init(2, qr.getCount(), 3); System.out.println("当前页: "+pageBean.getCurPage()); System.out.println("上页: "+pageBean.getPrePage()); System.out.println("下页: "+pageBean.getNextPage()); System.out.println("总记录数: "+pageBean.getRecordCnt()); System.out.println("每页显示最大记录数: "+pageBean.getMaxSize()); System.out.println("总页数: "+pageBean.getPageCnt()); } @Test public void findAllStudentByCondition() throws Exception{ DaoStudent daoStudent=DaoFactory.getDaoStudent(); /* * 模拟数据 */ int beginIndex=0; int maxSize=3; SearchStudent searchStudent=new SearchStudent(); // searchStudent.setJobname("CS"); QueryResult <Student> qr=daoStudent.findAllStudentByCondition(searchStudent,beginIndex, maxSize); if(qr!=null&&qr.getList()!=null){ for(Student st:qr.getList()){ System.out.println(st.getId()+" "+st.getMajor()); } } System.out.println("总的记录数:"+qr.getCount()); //计算上页 下页 总页等信息 PageBean pageBean=new PageBean(); pageBean.init(2, qr.getCount(), 3); System.out.println("当前页: "+pageBean.getCurPage()); System.out.println("上页: "+pageBean.getPrePage()); System.out.println("下页: "+pageBean.getNextPage()); System.out.println("总记录数: "+pageBean.getRecordCnt()); System.out.println("每页显示最大记录数: "+pageBean.getMaxSize()); System.out.println("总页数: "+pageBean.getPageCnt()); } }
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> <title>My JSP 'main.jsp' starting page</title> </head> <body> 学生管理系统 <br> <a href="${pageContext.request.contextPath }/addPersonServlet" target="mainFrane" title="学生信息录入">学生信息录入</a></br> <a href="${pageContext.request.contextPath }/ListServlet" target="mainFrane" title="学生信息录入">学生信息查询</a></br> <a href="${pageContext.request.contextPath }/ListConditionServlet" target="mainFrane" title="学生信息录入">学生信息高级查询</a></br> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%request.setCharacterEncoding("UTF-8"); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'list.jsp' starting page</title> </head> <body> <table border="1"> <input type="hidden" name="flag" id="flag" value="page"/> <tr> <th>编号</th> <th>姓名</th> <th>性别</th> <th>专业</th> </tr> <c:forEach items="${studentList}" var="student"> <tr> <td>${student.id }</td> <td>${student.username }</td> <td>${student.sex}</td> <td>${student.major }</td> </tr> </c:forEach> </table> 共有${pageBean.recordCnt }条记录 共${pageBean.pageCnt }页 当前是${pageBean.curPage }页 <!-- 第一种 --> <a href="${pageContext.request.contextPath }/ListServlet?curPage=1&maxSize=${pageBean.maxSize}">首页</a> <a href="${pageContext.request.contextPath }/ListServlet?curPage=${pageBean.prePage }&maxSize=${pageBean.maxSize}">上页</a> <a href="${pageContext.request.contextPath }/ListServlet?curPage=${pageBean.nextPage }&maxSize=${pageBean.maxSize}">下页</a> <a href="${pageContext.request.contextPath }/ListServlet?curPage=${pageBean.pageCnt }&maxSize=${pageBean.maxSize}">尾页</a> <br/> <!-- 第2种 --> <a href="javascript:toPage(1,${pageBean.maxSize})">首页</a> <a href="javascript:toPage(${pageBean.prePage },${pageBean.maxSize})">上页</a> <a href="javascript:toPage(${pageBean.nextPage },${pageBean.maxSize})">下页</a> <a href="javascript:toPage(${pageBean.pageCnt },${pageBean.maxSize})">尾页</a> <br/> </body> <script type="text/javascript"> function toPage(curPage,maxSize){ var hid=document.getElementById("flag"); var flag=hid.value; //更改flag值 hid.value="search"; flag=hid.value; var path="${pageContext.request.contextPath }/ListServlet?curPage="+curPage+"&maxSize="+maxSize+"&flag="+flag; window.location=path; } </script> </html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%request.setCharacterEncoding("UTF-8"); %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <form name="form1" action="${pageContext.request.contextPath }/ListConditionServlet" method="post" > <table border="1"> <!-- 标志位 若为search,表示 点击的是搜索 若值为page,点击的是上一页--> <input type="hidden" name="flag" id="flag" value="search"/> <tr> <td>学生姓名</td> <td><input type="text" id="cname" name="cname" value="${searchStudent.cname}"> <input type="hidden" id="old_cname" name="old_cname" value="${searchStudent.cname}"> </td> </tr> <tr> <td>jobName</td> <td><input type="text" id="jobname" name="jobname" value="${searchStudent.major}"> <input type="hidden" id="old_jobname" name="old_jobname" value="${searchStudent.major}"> </td> </tr> <tr> <td> </td> <td><input type="button" value="搜索" onclick="toSearch(1,${pageBean.maxSize})"></td> </tr> </table> </form> <table border="1"> <tr> <th>编号</th> <th>姓名</th> <th>性别</th> <th>专业</th> </tr> <c:forEach items="${listStudent}" var="student"> <tr> <td>${student.id }</td> <td>${student.username }</td> <td>${student.sex}</td> <td>${student.major }</td> </tr> </c:forEach> </table> 共有${pageBean.recordCnt }条记录 共${pageBean.pageCnt }页 当前是${pageBean.curPage }页 <!-- 第一种 --> <a href="${pageContext.request.contextPath }/ListConditionServlet?curPage=1&maxSize=${pageBean.maxSize}">首页</a> <a href="${pageContext.request.contextPath }/ListConditionServlet?curPage=${pageBean.prePage }&maxSize=${pageBean.maxSize}">上页</a> <a href="${pageContext.request.contextPath }/ListConditionServlet?curPage=${pageBean.nextPage }&maxSize=${pageBean.maxSize}">下页</a> <a href="${pageContext.request.contextPath }/ListConditionServlet?curPage=${pageBean.pageCnt }&maxSize=${pageBean.maxSize}">尾页</a> <br/> <!-- 第2种 --> <a href="javascript:toPage(1,${pageBean.maxSize})">首页</a> <a href="javascript:toPage(${pageBean.prePage },${pageBean.maxSize})">上页</a> <a href="javascript:toPage(${pageBean.nextPage },${pageBean.maxSize})">下页</a> <a href="javascript:toPage(${pageBean.pageCnt },${pageBean.maxSize})">尾页</a> <br/> </body> <script type="text/javascript"> function toPage(curPage,maxSize){ //更改flag值 /*document.getElementById("flag").value="page"; var path="${pageContext.request.contextPath }/ListConditionServlet?curPage="+curPage+"&maxSize="+maxSize; window.location=path;*/ document.getElementById("flag").value="page"; var action=document.forms[0].action; action=action+"?curPage="+curPage+"&maxSize="+maxSize; document.forms[0].action=action; document.forms[0].submit(); } function toSearch(curpage,maxSize){ document.getElementById("flag").value="search"; document.forms[0].submit(); } </script> </html>