struts2+spring+hibernate 实现分页
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了struts2+spring+hibernate 实现分页,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含11006字,纯文字阅读大概需要16分钟。
内容图文
![struts2+spring+hibernate 实现分页](/upload/InfoBanner/zyjiaocheng/1315/75376495306143399512f4372750040c.jpg)
在这里要感谢下这位博友发表的博文
http://www.blogjava.net/rongxh7/archive/2008/11/29/243456.html
通过对他代码的阅读,从而自己实现了网页分页功能,下面给大家分享下我的代码
1.entity实体类
我项目例子的实体类叫News
2.DAO接口的设计,定义一个NewsDAO接口,里面声明了两个方法:
public interface NewsDAO { public int getAllRowCount(String hql); public List<News> queryByPage(String hql, int offset, int pageSize); }
3.DAO层接口的实现类NewsDAOImpl类,并实现接口的两个方法:
public class NewsDAOImpl implements NewsDAO{ //注解注入属性实例 @Resource(name="mySessionFactory_mysql") private SessionFactory sessionFactory; /** * 通过hql语句得到数据库中记录总数 */ @Override publicint getAllRowCount(String hql) { Session session=sessionFactory.openSession(); Transaction tx=null; int allRows=0; try{ tx=session.beginTransaction(); Query query=session.createQuery(hql); allRows=query.getResultList().size(); tx.commit(); }catch (Exception e){ if(tx != null) { tx.rollback(); } e.printStackTrace(); }finally{ if(session!=null){ session.close(); } } return allRows; } /** * 使用hibernate提供的分页功能,得到分页显示的数据 */ @Override public List<News> queryByPage(String hql, int offset, int pageSize) { Session session=sessionFactory.openSession(); Transaction tx=null; List<News> list=null; try{ tx=session.beginTransaction(); Query query=session.createQuery(hql).setFirstResult(offset).setMaxResults(pageSize); list=query.getResultList(); tx.commit(); }catch(Exception e){ if(tx != null) { tx.rollback(); } e.printStackTrace(); }finally{ if(session!=null){ session.close(); } } return list; } }
4.定义了一个PageBean(每一页所需要的内容都存放在这个PageBean里面),里面用来存放网页每一页显示的内容:
public class PageBean { private List<News> list; //通过hql从数据库分页查询出来的list集合privateint allRows; //总记录数privateint totalPage; //总页数privateint currentPage; //当前页public List<News> getList() { return list; } publicvoid setList(List<News> list) { this.list = list; } publicint getAllRows() { return allRows; } publicvoid setAllRows(int allRows) { this.allRows = allRows; } publicint getTotalPage() { return totalPage; } publicvoid setTotalPage(int totalPage) { this.totalPage = totalPage; } publicint getCurrentPage() { return currentPage; } publicvoid setCurrentPage(int currentPage) { this.currentPage = currentPage; } /** * 得到总页数 * @param pageSize 每页记录数 * @param allRows 总记录数 * @return 总页数 */publicint getTotalPages(int pageSize, int allRows){ int totalPage = (allRows % pageSize == 0)? (allRows / pageSize): (allRows / pageSize) + 1; return totalPage; } /** * 得到当前开始记录号 * @param pageSize 每页记录数 * @param currentPage 当前页 * @return*/publicint getCurrentPageOffset(int pageSize, int currentPage){ int offset = pageSize * (currentPage - 1); return offset; } /** * 得到当前页, 如果为0 则开始第一页,否则为当前页 * @param page * @return*/publicint getCurPage(int page){ int currentPage = (page == 0)? 1: page; return currentPage; } }
5.Service层接口设计,定义一个NewsService接口,里面声明了一个方法,返回一个PageBean:
public interface NewsService { public PageBean getPageBean(int pageSize,int page); }
6.Service层接口实现类NewsServiceImpl类,实现NewsService接口的方法:
public class NewsServiceImpl implements NewsService{ //注解注入属性实例 @Resource(name="myNewsDao") private NewsDAO newsDao; @Resource(name="myPageBean") private PageBean pageBean; /** * pageSize为每页显示的记录数 * page为当前显示的网页 */ @Override public PageBean getPageBean(int pageSize, int page) { String hql="from News"; //总记录数int allRows=newsDao.getAllRowCount(hql); //总页数int totalPage=pageBean.getTotalPages(pageSize,allRows); //当前页int currentPage=pageBean.getCurPage(page); //锚点(从第几条数据开始查询)int offset=pageBean.getCurrentPageOffset(pageSize, currentPage); List<News> list = newsDao.queryByPage(hql, offset, pageSize); pageBean.setList(list); pageBean.setAllRows(allRows); pageBean.setCurrentPage(currentPage); pageBean.setTotalPage(totalPage); return pageBean; } }
7.Action层设计,定义一个NewsAction:
public class NewsAction extends ActionSupport { //注解注入属性实例 @Resource(name="myNewsService") private NewsService newsService; privateint page; publicint getPage() { return page; } publicvoid setPage(int page) { this.page = page; } @Override public String execute(){ //表示每页显示5条记录,page表示当前网页 PageBean pageBean = newsService.getPageBean(5, page); HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("pageBean", pageBean); return SUCCESS; } }
9.配置struts.xml文件
<? xml version="1.0" encoding="UTF-8" ?> <! DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd" > < struts > <!-- 告知Struts2运行时使用Spring来创建对象 --> < constant name ="struts.objectFactory" value ="spring" /> < package name ="mypck001" extends ="struts-default" namespace ="/" > < action name ="NewsAction" class ="myNewsAction" method ="execute" > < result name ="success" >/WEB-INF/jsp/index.jsp</result></action></package></struts>
10.配置applicationContext.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:p ="http://www.springframework.org/schema/p" xmlns:aop ="http://www.springframework.org/schema/aop" xmlns:context ="http://www.springframework.org/schema/context" xmlns:jee ="http://www.springframework.org/schema/jee" xmlns:tx ="http://www.springframework.org/schema/tx" xsi:schemaLocation =" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd" > <!-- 原理:自动注入processor解析器,用来解析注解 --> < context:annotation-config /> < context:property-placeholder location ="classpath:jdbc.properties" /> < bean id ="myNewsAction" class ="sshPage.action.NewsAction" scope ="prototype" > </ bean > < bean id ="myNewsService" class ="sshPage.service.NewsServiceImpl" scope ="prototype" > </ bean > < bean id ="myNewsDao" class ="sshPage.dao.NewsDAOImpl" scope ="prototype" > </ bean > < bean id ="myPageBean" class ="sshPage.pageBean.PageBean" scope ="prototype" > </ bean > < bean id ="mySessionFactory_mysql" class ="org.springframework.orm.hibernate5.LocalSessionFactoryBean" > < property name ="dataSource" ref ="mysql_DataSource" ></ property > < property name ="hibernateProperties" > < props > < prop key ="hibernate.dialect" >org.hibernate.dialect.MySQL5Dialect</prop><prop key="hibernate.show_sql">true</prop><prop key="hibernate.format_sql">true</prop><prop key="hibernate.connection.autocommit">false</prop><prop key="hibernate.hbm2ddl.auto">update</prop></props></property><property name="mappingResources"><list><value>sshPage/entity/News.hbm.xml</value></list></property></bean><!-- 数据库连接池 mysql_DataSource--><!-- c3p0 --><bean id="mysql_DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${mysql.driver}"/><property name="jdbcUrl" value="${mysql.url}"/><property name="user" value="${mysql.userName}"/><property name="password" value="${mysql.password}"/><property name="idleConnectionTestPeriod" value="300"></property><property name="maxIdleTime" value="900"></property><property name="maxPoolSize" value="2"></property></bean></beans>
11.最后也就是JSP页面index.jsp:
<% @ page language = " java " contentType = " text/html; charset=UTF-8 " pageEncoding = " UTF-8 " %> <% @ taglib uri = " /struts-tags " prefix = " s " %> <% @ page import = " java.util.* " %> <! 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" > < title >Insert title here</title><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 ="NewsAction"; returnfalse; } returntrue; } </script></head><body><h1><font color="blue">分页查询</font></h1><hr><table border="1" align="center" bordercolor="yellow" width="50%"><tr><th>Id</th><th>Title</th><th>Content</th><th>Begintime</th><th>Username</th></tr><s:iterator value="#request.pageBean.list" id="news"><tr><td><s:property value="#news.id"/></td><td><s:property value="#news.title"/></td><td><s:property value="#news.content"/></td><td><s:date name="#news.begintime" format="yyyy年MM月dd日"></s:date></td><td><s:property value="#news.username"></s:property></td></tr></s:iterator></table><b></b><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><font size="5">第<font color="red"><s:property value="#request.pageBean.currentPage"/></font>页 </font><s:if test="#request.pageBean.currentPage == 1"> 首页 上一页 </s:if><s:else><a href="NewsAction.action">首页</a> <a href="NewsAction.action?page=<s:property value="#request.pageBean.currentPage - 1"/>">上一页</a></s:else><s:if test="#request.pageBean.currentPage != #request.pageBean.totalPage"><a href="NewsAction.action?page=<s:property value="#request.pageBean.currentPage + 1"/>">下一页</a> <a href="NewsAction.action?page=<s:property value="#request.pageBean.totalPage"/>">尾页</a></s:if><s:else> 下一页 尾页 </s:else></center><br><center><form action="NewsAction" onsubmit="return validate();"><font size="4">跳转至</font><input type="text" size="2" value=‘<s:property value="#request.pageBean.currentPage"/>‘ name="page">页 <input type="submit" value="跳转"></form></center></body></html>
页面效果图如下:
实现分页就差不多到这了,如果有不懂的地方,可以评论区给我留言,谢谢!
原文:http://www.cnblogs.com/qq1272850043/p/5954358.html
内容总结
以上是互联网集市为您收集整理的struts2+spring+hibernate 实现分页全部内容,希望文章能够帮你解决struts2+spring+hibernate 实现分页所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。