Thinking of learning something new every day, today I prepared this hibernate+struts2 to implement the page paging function. The following is the source code.
1. Design of DAO layer interface, define a PersonDAO interface, and declares two methods:
public interface PersonDAO{ public List<Person> queryByPage(String hql, int offset, int pageSize); public int getAllRowCount(String hql);}2. The implementation of the DAO layer interface is PersonDAOImpl class, and two methods are implemented:
public class PersonDAOImpl implements PersonDAO{ /** * Get the total number of records in the database through the hql statement*/ @Override public int getAllRowCount(String hql) { Session session = HibernateUtil.openSession(); 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 { HibernateUtil.closeSession(session); } return allRows; } /** * Use the paging function provided by hibernate to get the data displayed by the pagination*/ @SuppressWarnings("unchecked") @Override public List<Person> queryByPage(String hql, int offset, int pageSize) { Session session = HibernateUtil.openSession(); Transaction tx = null; List<Person> 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 { HibernateUtil.closeSession(session); } return list; }}3. Define a PageBean (the content required for each page is stored in this PageBean), which is used to store the content displayed on each page of the web page:
public class PageBean{ private List<Person> list; //list collection query from database paging through hql private int allRows; //Total records private int totalPage; //Total pages private int currentPage; //The current page public List<Person> getList() { return list; } public void setList(List<Person> 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; } /** * Get the total number of pages* @param pageSize Number of records per page* @param allRows Total records* @return Total pages*/ public int getTotalPages(int pageSize, int allRows) { int totalPage = (allRows % pageSize == 0)? (allRows / pageSize): (allRows / pageSize) + 1; return totalPage; } /** * Get the current start record number* @param pageSize Number of records per page* @param currentPage Current page* @return */ public int getCurrentPageOffset(int pageSize, int currentPage) { int offset = pageSize * (currentPage - 1); return offset; } /** * Get the current page, if it is 0, the first page will start, otherwise it is the current page* @param page * @return */ public int getCurPage(int page) { int currentPage = (page == 0)? 1: page; return currentPage; } }4. Service layer interface design, define a PersonService interface, declare a method, and return a PageBean:
public interface PersonService{ public PageBean getPageBean(int pageSize, int page);}5. The Service layer interface implements the PersonServiceImpl class, implementing the only method:
public class PersonServiceImpl implements PersonService{ private PersonDAO personDAO = new PersonDAO Impl(); /** * pageSize is the number of records displayed per page* page is the currently displayed web page*/ @Override public PageBean getPageBean(int pageSize, int page) { PageBean pageBean = new PageBean(); String hql = "from Person"; int allRows = personDAO.getAllRowCount(hql); int totalPage = pageBean.getTotalPages(pageSize, allRows); int currentPage = pageBean.getCurPage(page); int offset = pageBean.getCurrentPageOffset(pageSize, currentPage); List<Person> list = personDAO.queryByPage(hql, offset, pageSize); pageBean.setList(list); pageBean.setAllRows(allRows); pageBean.setCurrentPage(currentPage); pageBean.setTotalPage(totalPage); return pageBean; }}6. Action layer design, define a PersonAction:
public class PersonAction extends ActionSupport{ private PersonService personService = new PersonServiceImpl(); private int page; public int getPage() { return page; } public void setPage(int page) { this.page = page; } @Override public String execute() throws Exception { // means 5 records are displayed per page, page means the current web page PageBean pageBean = personService.getPageBean(5, page); HttpServletRequest request = ServletActionContext.getRequest(); request.setAttribute("pageBean", pageBean); return SUCCESS; }}7. Auxiliary design, HibernateUtil:
public class HibernateUtil{ private static SessionFactory sessionFactory; static { sessionFactory = new Configuration().configure().buildSessionFactory(); } public static Session openSession() { Session session = sessionFactory.openSession(); return session; } public static void closeSession(Session session) { if(session != null) { session.close(); } } }8. Finally, the pagePerson.jsp is displayed on the pagination page:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="s" uri="/struts-tags"%><html> <head> <base href="<%=basePath%>"> <title>My JSP 'pagePerson.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <script type="text/javascript"> function validate() { var page = document.getElementsByName("page")[0].value; if(page > <s:property value="#request.pageBean.totalPage"/>) { alert("The number of pages you enter is greater than the maximum number of pages, and the page will jump to the homepage!"); window.document.location.href = "personAction"; return false; } return true; } </script> </head> <body> <h1><font color="blue">Pagination query</font></h1><hr> <table align="center" bordercolor="yellow"> <tr> <th>Serial number</th> <th>Name</th> <th>Age</th> </tr> <s:iterator value="#request.pageBean.list" id="person"> <tr> <th><s:property value="#person.id"/></th> <th><s:property value="#person.age"/></th> </tr> </s:iterator> </table> <center> <font size="5">Total<font color="red"><s:property value="#request.pageBean.totalPage"/></font> pages</font> <font size="5">Total<font color="red"><s:property value="#request.pageBean.allRows"/></font> records</font><br><br><s:if test="#request.pageBean.currentPage == 1"> Home Previous Page</s:if> <s:else> <a href="personAction.action">Home</a> <a href="personAction.action?page=<s:property value="#request.pageBean.currentPage - 1"/>">Previous page</a> </s:else> <s:if test="#request.pageBean.currentPageBean.currentPage != #request.pageBean.totalPage"> <a href="personAction.action?page=<s:property value="#request.pageBean.currentPage + 1"/>">Next page</a> <a href="personAction.action?page=<s:property value="#request.pageBean.totalPage"/>">Last Page</a> </s:if> <s:else> Next PageLast Page</s:else> </center><br> <center> <form action="personAction" onsubmit="return validate();"> <font size="4">Skip to</font> <input type="text" size="2" name="page">Page<input type="submit" value="jump"> </form> </center> </body></html>At this point, the code part of the web page paging function implementation of hibernate+struts2 is completed. The configuration files of hibernate and struts are not listed, and those are not the key points!
The page effect is as follows:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.