hibernate和struts实现分页
仓促把功能进行实现一下 类与类之间也没有进行MVC式分开 重要的是逻辑 记录一下 希望其中的些许代码逻辑对你有用
TUserDaoImpl---dao层的实现 package com.pers.hoobey; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import java.util.List; /** * Created by hoobey on 2017/9/7. */ public class TUserDaoImpl implements TUserDao { @Override public TUser busOper(TUser bean, int oper) { Session s = HibernateSessionFactory.getSession(); Transaction tx = s.getTransaction(); TUser user = new TUser(); try { tx.begin(); user = bean; //evict变为脱管状态,脱管对象通过session的save,update,saveOrUpdate,lock等方法变回持久化对象 s.evict(bean); if (oper == -1) { s.delete(bean); } else if (oper == 0) { s.update(bean); } else if (oper == 1) { s.save(bean); } else { user = (TUser) s.get(TUser.class, bean.getId()); } tx.commit(); } catch (Exception ex) { ex.printStackTrace(); tx.rollback();//事务回滚 return null; } s.evict(bean); s.close(); return user; } /** * 使用hibernate提供的分页功能,得到分页显示的数据 * select * from t_user limit 0,3; * 0=offset * 3=pageSize */ @SuppressWarnings("unchecked") @Override public List<TUser> queryByPage(String hql, int offset, int pageSize) { Session session = HibernateSessionFactory.getSession(); Transaction tx = null; List<TUser> list = null; try { tx = session.beginTransaction(); Query query = session.createQuery(hql).setFirstResult(offset).setMaxResults(pageSize); list = query.list(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } e.printStackTrace(); } finally { HibernateSessionFactory.closeSession(); } return list; } /** * 通过hql语句得到数据库中记录总数 */ @Override public int getAllRowCount(String hql) { Session session = HibernateSessionFactory.getSession(); Transaction tx = null; int allRows = 0; try { tx = session.beginTransaction(); Query query = session.createQuery(hql); allRows = query.list().size(); tx.commit(); } catch (Exception e) { if (tx != null) { tx.rollback(); } e.printStackTrace(); } finally { HibernateSessionFactory.closeSession(); } return allRows; } }
2.PageBean--每一页显示的信息内容 package com.pers.hoobey; import java.util.List; /** * Created by hoobey on 2017/9/7. * (每一页所需要的内容都存放在这个PageBean里面),里面用来存放网页每一页显示的内容 */ public class PageBean { private List<TUser> list; //通过hql从数据库分页查询出来的list集合 private int allRows; //总记录数 private int totalPage; //总页数 private int currentPage; //当前页 /** * 得到总页数 * * @param pageSize 每页记录数 * @param allRows 总记录数 * @return 总页数 */ public int getTotalPages(int pageSize, int allRows) { int totalPage = (allRows % pageSize == 0) ? (allRows / pageSize) : (allRows / pageSize) + 1; return totalPage; } /** * 得到当前开始记录号 * * @param pageSize 每页记录数 * @param currentPage 当前页 * @return */ public int getCurrentPageOffset(int pageSize, int currentPage) { int offset = pageSize * (currentPage - 1); return offset; } /** * 得到当前页, 如果为0 则开始第一页,否则为当前页 * * @param page * @return */ public int getCurPage(int page) { int currentPage = (page == 0) ? 1 : page; return currentPage; } public List<TUser> getList() { return list; } public void setList(List<TUser> list) { this.list = list; } public int getAllRows() { return allRows; } public void setAllRows(int allRows) { this.allRows = allRows; } public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } }
3.TUserServiceImpl---service层实现 package com.pers.hoobey; import java.util.Iterator; import java.util.List; /** * Created by hoobey on 2017/9/7. */ public class TUserServiceImpl implements TUserService { private TUserDaoImpl tUserDaoImpl = new TUserDaoImpl(); /** * pageSize为每页显示的记录数 * page为当前显示的页数 从0开始 */ @Override public PageBean getPageBean(int pageSize, int page) { PageBean pageBean = new PageBean(); String hql = "from TUser limit "; int allRows = tUserDaoImpl.getAllRowCount(hql);//总记录数 int totalPage = pageBean.getTotalPages(pageSize, allRows);//总页数 int currentPage = pageBean.getCurPage(page);//当前页 int offset = pageBean.getCurrentPageOffset(pageSize, currentPage);//当前页是 从1开始 要减去1 默认从0开始 //此处就隐含了分页查询 比对 select * from user limit "+(pageNo-1)*pageSize+","+pageSize; List<TUser> list = tUserDaoImpl.queryByPage(hql, offset, pageSize); /*打印输出看一波 非常正确 所有的数据都存进了pageBean*/ Iterator<TUser> iterator = list.iterator(); while(iterator.hasNext()){ System.out.println("查询当前分页显示的数据是:"+iterator.next().toString()); } System.out.println("总记录数:"+allRows); System.out.println("当前页面是:"+currentPage); System.out.println("总页数是:"+totalPage); pageBean.setList(list); pageBean.setAllRows(allRows); pageBean.setCurrentPage(currentPage); pageBean.setTotalPage(totalPage); return pageBean; } }
4.TUserAction--action的定义 package com.pers.hoobey; import com.opensymphony.xwork2.ActionSupport; import org.apache.struts2.ServletActionContext; import org.hibernate.Criteria; import org.hibernate.Session; import javax.servlet.http.HttpServletRequest; import java.util.List; public class TUserAction extends ActionSupport { private static final long serialVersionUID = 1L; private TUser user; private List<TUser> dataobject;//保存所有TUser数据集合 TUserDaoImpl tUserDaoImpl = new TUserDaoImpl(); TUserServiceImpl tUserServiceImpl = new TUserServiceImpl(); private int page; //查询所有 public String execute() throws Exception { Session session = HibernateSessionFactory.getSession(); Criteria query = session.createCriteria(TUser.class); this.dataobject = (List<TUser>)query.list(); for(TUser user : dataobject){ System.out.println("id="+user.getId()+"name="+user.getName()); } session.close(); return SUCCESS; } // 增加数据 public String addLine() throws Exception { System.out.print(user.getName());// user里面有内容 user = tUserDaoImpl.busOper(user, 1); if (user == null) return ERROR; return SUCCESS; } //修改数据 public String updLine() throws Exception{ user= tUserDaoImpl.busOper(user, 0); if(user==null) return ERROR; return SUCCESS; } //删除数据 public String delLine() throws Exception{ user= tUserDaoImpl.busOper(user, -1);//设计的很巧妙 if(user==null) return ERROR; return SUCCESS; } //当前页数显示数据 public String PageAll() throws Exception{ //表示每页显示3条记录,page表示当前网页 System.out.println("点击首页链接,进来了,返回出pageBean对象"); PageBean pageBean = tUserServiceImpl.getPageBean(3, page); System.out.println(page); HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("pageBean", pageBean);//通过struts.xml的配置把pageBean值送到jsps/Alldata.jsp return SUCCESS; } public TUser getUser() { return user; } public void setUser(TUser user) { this.user = user; } public List<TUser> getDataobject() { return dataobject; } public void setDataobject(List<TUser> dataobject) { this.dataobject = dataobject; } public int getPage() {return page;} public void setPage(int page) {this.page = page;} }
5.Alldata.jsp--页面信息显示 <%@ page language="java" import="java.util.*,com.pers.hoobey.*" pageEncoding="utf-8"%> <%@ taglib uri="/struts-tags" prefix="s"%> <% TUser user = new TUser(); %> <!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"> <script type="text/javascript"> function validate() { var page = document.getElementsByName("page")[0].value; if (page > <s:property value="#request.pageBean.totalPage"/>) { alert("你输入的页数大于最大页数,页面将跳转到首页!"); window.document.location.href = "TUserAction"; return false; } return true; } </script> </head> <body> HQL 查询结果显示如下: <h1><font color="blue">分页查询</font></h1> <hr> <br> <table align="center"> <tr> <td>序号</td> <td>姓名</td> <td>操作1</td> <td>操作2</td> </tr> <%--#request.pageBean.list 数据从TUserServiceImpl获取存入到PageBean--%> <s:iterator value="#request.pageBean.list" id="tUser"> <tr> <td><s:property value="#tUser.id" /></td> <td><s:property value="#tUser.name" /></td> <!-- 修改不同id对应的数据 --> <td><a href="<%=request.getContextPath() %>/edit.jsp?user.id=<s:property value="#tUser.id" />">修改</a></td> <td><a href="delline.action?user.id=<s:property value="#tUser.id" />">删除</a></td> </tr> </s:iterator> </table> <%--进行分页的页面布局--%> <center> <font size="5">共<font color="red"><s:property value="#request.pageBean.totalPage" /></font>页 </font> <font size="5">共<font color="red"><s:property value="#request.pageBean.allRows" /></font>条记录</font><br><br> <s:if test="#request.pageBean.currentPage == 1"> 首页 上一页 </s:if> <s:else> <%--进入此展示页面 必须点击首页链接 才会触动action去执行逻辑函数--%> <a href="TUserAction.action">首页</a> <a href="TUserAction.action?page=<s:property value="#request.pageBean.currentPage - 1"/>">上一页</a> </s:else> <s:if test="#request.pageBean.currentPage != #request.pageBean.totalPage"> <a href="TUserAction.action?page=<s:property value="#request.pageBean.currentPage + 1"/>">下一页</a> <a href="TUserAction.action?page=<s:property value="#request.pageBean.totalPage"/>">尾页</a> </s:if> <s:else> 下一页 尾页 </s:else> </center> <br> <center> <form action="TUserAction" onsubmit="return validate();"> <font size="4">跳转至</font> <input type="text" size="2" name="page">页 <input type="submit" value="跳转"> </form> </center> </body> </html>
你们都是有经验的开发人员