在写这篇博客之前,先深深吸口气.因为这种弱智的分页显示会让很多JAVA的学习者嗤之以鼻.
我在网络上找了很多关于Hibernate分页的东西,一直得不到要领,又是些Pagebean又是什么东东的,结果把他们的代码复制过来,数据库建好,包导进去.........等我忙了半天之后,还是出错.
我是那种喜欢看着别人的代码,运行起来之后才去分析代码为什么这样.这样或者那样的页面效果是怎么样实现的.可是如果让我先看别人的代码,然后再运行,我不太喜欢.
于是今天豁出去了,做了一个分页的功能.
代码全部复制过来.尽量说一点废话解释下.(如果谁有完整的分页代码,请给我个连接.或者QQ461628072联系)
1.建立两个JSP页面(JSP页面需要用到Struts标签,所以要导入Struts-----我用的是struts1.X版本的.)
index.jsp 和 ss.jsp 代码如下
- <%@ taglib prefix="logic" uri="/WEB-INF/struts-logic.tld"%>
- <%@ taglib prefix="bean" uri="/WEB-INF/struts-bean.tld"%>
- <%@ taglib prefix="html" uri="/WEB-INF/struts-html.tld"%>
- <%@ page language="java" import="java.util.*" pageEncoding="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>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'index.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">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
- -->
- </head>
- <body>
- <logic:notEmpty name="list">
- <logic:iterate id="ls" name="list">
- <bean:write property="name" name="ls" />
- </logic:iterate>
- </logic:notEmpty>
- <html:link href="/page/search.do?action=firstPage&page=1" mce_href="page/search.do?action=firstPage&page=1">首页信息</html:link>
- </body>
- </html>
- <%@ page language="java" pageEncoding="UTF-8"%>
- <%@ taglib prefix="logic" uri="/WEB-INF/struts-logic.tld"%>
- <%@ taglib prefix="bean" uri="/WEB-INF/struts-bean.tld"%>
- <%@ taglib prefix="html" uri="/WEB-INF/struts-html.tld"%>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme() + "://"
- + request.getServerName() + ":" + request.getServerPort()
- + path + "/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>My JSP 'ss.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">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css">
- -->
- </head>
- <body>
- <logic:notEmpty name="list">
- <table bgcolor="green" width="400" border="0" cellspacing="1">
- <logic:iterate id="ls" name="list">
- <tr style="background-color: white; height: 30px;">
- <td>
- <bean:write property="name" name="ls" />
- </td>
- <td>
- <bean:write property="sex" name="ls" />
- </td>
- </tr>
- </logic:iterate>
- </table>
- </logic:notEmpty>
- <%
- String pg = (String) request.getAttribute("page");
- int pp = 0;
- if (pg != null || !pg.equals(""))
- pp = Integer.parseInt(pg);
- %>
- 当前显示的数据是<%=pp%>页
- <html:link href="/page/search.do?action=firstPage&page=1" mce_href="page/search.do?action=firstPage&page=1">首页信息</html:link>
- <%
- int last = pp - 1;
- String l = Integer.toString(last);
- %>
- <a href="/page/search.do?action=lastPage&page=<%=l%" mce_href="page/search.do?action=lastPage&page=<%=l%">>上一页</a>
- <%
- int next = pp + 1;
- String n = Integer.toString(next);
- %>
- <a href="/page/search.do?action=nextPage&page=<%=n%" mce_href="page/search.do?action=nextPage&page=<%=n%">>下一页</a>
- <html:link href="/page/search.do?action=endPage" mce_href="page/search.do?action=endPage">最后一页</html:link>
- </body>
- </html>
JSP页面完成之后,就是关于Hibernate类的东东了.
TUser.java代码 (这些代码都是使用MyEclipse6.0 自动生成的,不是自己写的.
(以下HibernateSessionFactory.java hibernate.cfg.xml /TUser.hbm.xml 也都是通过自动生成的,如果你懒得生成,全部复制过去.)
- package hibernate;
- /**
- * TUser entity.
- *
- * @author MyEclipse Persistence Tools
- */
- public class TUser implements java.io.Serializable {
- // Fields
- private Integer id;
- private String name;
- private String sex;
- // Constructors
- /** default constructor */
- public TUser() {
- }
- /** minimal constructor */
- public TUser(Integer id) {
- this.id = id;
- }
- /** full constructor */
- public TUser(Integer id, String name, String sex) {
- this.id = id;
- this.name = name;
- this.sex = sex;
- }
- // Property accessors
- public Integer getId() {
- return this.id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getName() {
- return this.name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getSex() {
- return this.sex;
- }
- public void setSex(String sex) {
- this.sex = sex;
- }
- }
HibernateSessionFactory.java代码
- package hibernate;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import org.hibernate.cfg.Configuration;
- /**
- * Configures and provides access to Hibernate sessions, tied to the
- * current thread of execution. Follows the Thread Local Session
- * pattern, see {@link http://hibernate.org/42.html }.
- */
- public class HibernateSessionFactory {
- /**
- * Location of hibernate.cfg.xml file.
- * Location should be on the classpath as Hibernate uses
- * #resourceAsStream style lookup for its configuration file.
- * The default classpath location of the hibernate config file is
- * in the default package. Use #setConfigFile() to update
- * the location of the configuration file for the current session.
- */
- private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
- private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
- private static Configuration configuration = new Configuration();
- private static org.hibernate.SessionFactory sessionFactory;
- private static String configFile = CONFIG_FILE_LOCATION;
- static {
- try {
- configuration.configure(configFile);
- sessionFactory = configuration.buildSessionFactory();
- } catch (Exception e) {
- System.err
- .println("%%%% Error Creating SessionFactory %%%%");
- e.printStackTrace();
- }
- }
- private HibernateSessionFactory() {
- }
- /**
- * Returns the ThreadLocal Session instance. Lazy initialize
- * the <code>SessionFactory</code> if needed.
- *
- * @return Session
- * @throws HibernateException
- */
- public static Session getSession() throws HibernateException {
- Session session = (Session) threadLocal.get();
- if (session == null || !session.isOpen()) {
- if (sessionFactory == null) {
- rebuildSessionFactory();
- }
- session = (sessionFactory != null) ? sessionFactory.openSession()
- : null;
- threadLocal.set(session);
- }
- return session;
- }
- /**
- * Rebuild hibernate session factory
- *
- */
- public static void rebuildSessionFactory() {
- try {
- configuration.configure(configFile);
- sessionFactory = configuration.buildSessionFactory();
- } catch (Exception e) {
- System.err
- .println("%%%% Error Creating SessionFactory %%%%");
- e.printStackTrace();
- }
- }
- /**
- * Close the single hibernate session instance.
- *
- * @throws HibernateException
- */
- public static void closeSession() throws HibernateException {
- Session session = (Session) threadLocal.get();
- threadLocal.set(null);
- if (session != null) {
- session.close();
- }
- }
- /**
- * return session factory
- *
- */
- public static org.hibernate.SessionFactory getSessionFactory() {
- return sessionFactory;
- }
- /**
- * return session factory
- *
- * session factory will be rebuilded in the next call
- */
- public static void setConfigFile(String configFile) {
- HibernateSessionFactory.configFile = configFile;
- sessionFactory = null;
- }
- /**
- * return hibernate configuration
- *
- */
- public static Configuration getConfiguration() {
- return configuration;
- }
- }
接着是配置文件: TUser.hbm.xml
- <?xml version="1.0" encoding="utf-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <!--
- Mapping file autogenerated by MyEclipse Persistence Tools
- -->
- <hibernate-mapping>
- <class name="hibernate.TUser" table="t_user" catalog="test">
- <id name="id" type="java.lang.Integer">
- <column name="id" />
- <generator class="assigned" />
- </id>
- <property name="name" type="java.lang.String">
- <column name="name" length="50" />
- </property>
- <property name="sex" type="java.lang.String">
- <column name="sex" length="11" />
- </property>
- </class>
- </hibernate-mapping>
配置文件:hibernate.cfg.xml
- <?xml version='1.0' encoding='UTF-8'?>
- <!DOCTYPE hibernate-configuration PUBLIC
- "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
- <!-- Generated by MyEclipse Hibernate Tools. -->
- <hibernate-configuration>
- <session-factory>
- <property name="connection.username">root</property>
- <property name="connection.url">
- jdbc:mysql://localhost:3306/MySQL
- </property>
- <property name="dialect">
- org.hibernate.dialect.MySQLDialect
- </property>
- <property name="myeclipse.connection.profile">MySQL</property>
- <property name="connection.password">root</property>
- <property name="connection.driver_class">
- com.mysql.jdbc.Driver
- </property>
- <mapping resource="hibernate/TUser.hbm.xml" />
- </session-factory>
- </hibernate-configuration>
接着我写了一个DAO .只有一个查询的方法:UserDAO.JAVA
- package hibernate;
- import org.hibernate.Query;
- import org.hibernate.Session;
- /*******************************************************************************
- * @Auther 李成
- * @Create_Date Apr 20, 2009 4:02:24 PM
- * @Company 昆明英聚科技有限责任公司
- ******************************************************************************/
- public class UserDAO {
- /**
- * 获取所有用户的信息,返回类型为Query.
- *
- * @return
- */
- public Query getUserQuery() {
- Session session = HibernateSessionFactory.getSession();
- String hql = "from TUser";
- Query query = session.createQuery(hql);
- return query;
- }
- }
接下来的代码全部是我自己写的.大家可以先行复制,然后部署到项目里面.
PageBean.java
- package page.page;
- import java.util.List;
- import org.hibernate.Query;
- /*******************************************************************************
- * @Auther 李成
- * @Create_Date Apr 20, 2009 4:04:38 PM
- * @Company 昆明英聚科技有限责任公司
- ******************************************************************************/
- public class PageBean {
- private int pagesize = 5; // 每页显示5条数据.
- /**
- * 获取到指定页的信息
- *
- * @param query
- * @param page
- * @return
- */
- public List getNumberPage(Query query, int page) {
- List list = query.setFirstResult((page - 1) * pagesize).setMaxResults(
- pagesize).list();
- return list;
- }
- }
SearchForm.java
- package page.action;
- import org.apache.struts.action.ActionForm;
- public class SearchForm extends ActionForm {
- private String action;
- private String page;
- public String getAction() {
- return action;
- }
- public void setAction(String action) {
- this.action = action;
- }
- public String getPage() {
- return page;
- }
- public void setPage(String page) {
- this.page = page;
- }
- }
SearchAction.java
- package page.action;
- import hibernate.UserDAO;
- import java.util.List;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts.action.Action;
- import org.apache.struts.action.ActionForm;
- import org.apache.struts.action.ActionForward;
- import org.apache.struts.action.ActionMapping;
- import org.hibernate.Query;
- import page.page.PageBean;
- import page.service.SearchService;
- /*******************************************************************************
- * @Auther 李成
- * @Create_Date Apr 20, 2009 4:17:22 PM
- * @Company 昆明英聚科技有限责任公司
- ******************************************************************************/
- public class SearchAction extends Action {
- @Override
- public ActionForward execute(ActionMapping mapping, ActionForm form,
- HttpServletRequest request, HttpServletResponse response)
- throws Exception {
- // TODO Auto-generated method stub
- SearchForm searchForm = (SearchForm) form;
- String action = searchForm.getAction();
- String page = searchForm.getPage();
- System.out.println("action = " + action + " and page = " + page);
- UserDAO dao = new UserDAO();
- Query query = dao.getUserQuery();
- if (action.equals("firstPage")) {
- SearchService service = new SearchService();
- List<Object> list = service.getList(query, page);
- request.setAttribute("page", "1");
- request.setAttribute("list", list);
- } else if (action.equals("lastPage") || action.equals("nextPage")) { // 获得上一页/下一页的数据
- SearchService service = new SearchService();
- List<Object> list = service.getList(query, page);
- request.setAttribute("page", page);
- request.setAttribute("list", list);
- } else {
- request.setAttribute("page", "1");
- }
- return mapping.findForward("success");
- }
- }
SearchService.java
- package page.service;
- import java.util.List;
- import org.hibernate.Query;
- import page.page.PageBean;
- /*******************************************************************************
- * @Auther 李成
- * @Create_Date Apr 20, 2009 4:20:23 PM
- * @Company 昆明英聚科技有限责任公司
- ******************************************************************************/
- public class SearchService {
- public List<Object> getList(Query query, String page) {
- List<Object> list = null;
- PageBean bean = new PageBean();
- int pa = Integer.parseInt(page); // 把字符串的页数转换成整数
- list = bean.getNumberPage(query, pa);
- return list;
- }
- }
最后是配置文件:
struts-config.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
- <struts-config>
- <data-sources />
- <form-beans>
- <form-bean name="form" type="page.action.SearchForm"></form-bean>
- </form-beans>
- <global-exceptions />
- <global-forwards />
- <action-mappings>
- <action path="/search" name="form"
- type="page.action.SearchAction">
- <forward name="success" path="/ss.jsp"></forward>
- </action>
- </action-mappings>
- <message-resources parameter="ApplicationResources" />
- </struts-config>
web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
- <servlet>
- <servlet-name>action</servlet-name>
- <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
- <init-param>
- <param-name>config</param-name>
- <param-value>/WEB-INF/struts-config.xml</param-value>
- </init-param>
- <init-param>
- <param-name>debug</param-name>
- <param-value>3</param-value>
- </init-param>
- <init-param>
- <param-name>detail</param-name>
- <param-value>3</param-value>
- </init-param>
- <load-on-startup>0</load-on-startup>
- </servlet>
- <servlet-mapping>
- <servlet-name>action</servlet-name>
- <url-pattern>*.do</url-pattern>
- </servlet-mapping>
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- </web-app>
我实现的效果如下..................................