jsp自定义标签+jpa+hibernate+struts2实现的分页

先看web.xml代码:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <filter>
  	<filter-name>struts2</filter-name>
  	<filter-class>
  		org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  	</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>struts2</filter-name>
  	<url-pattern>*.action</url-pattern>
  </filter-mapping>
  
  <jsp-config>
	  <taglib>
		<taglib-uri>/tags/lpm</taglib-uri>           //跟上面定义的uri值一样
		<taglib-location>/WEB-INF/lpm.tld</taglib-location>   //写文件所在的路径
	  </taglib>
  </jsp-config>
  
</web-app>

 在看/WEB-INF/lpm.tld文件代码:

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>
    <tlibversion>1.2</tlibversion>
    <jspversion>1.1</jspversion>
    <shortname>lpm</shortname>           <!-- 使用标签时的前缀 -->
    <uri>/tags/lpm</uri>
    
    <tag>
        <name>mytaglib</name>            <!-- 使用时跟在前缀后的名字,组合成一个标签 -->
        <tagclass>com.china.page.taglibpage</tagclass>      <!-- 在这里写刚才定义好的类 -->
        <bodycontent>jsp</bodycontent>  <!--可以为empty和jsp,如果为empty,开始标签和结束标签之间如果有jsp内容就会出错  -->
        <attribute>
          <name>formid</name>       <!--定义此标签可以用的属性名-->
          <required>true</required>   <!-- 表示这个属性是否可以为空,为true一定要有属性值 -->
          <rtexprvalue>true</rtexprvalue>   <!-- 表示是否可以使用JSP表达式 -->
        </attribute>
    </tag>
    
</taglib>

 

 

首页index.jsp加一个跳转:

     <a href="lpm/step.action">aaa</a>

 action代码:

package com.china.action;


import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;

import com.china.model.persion;
import com.china.page.Pageinfo;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Namespace("/lpm")
public class Lpmcon extends ActionSupport{

	@Action(value="step",
			results={@Result(name="Today",location="/test/abc.jsp")})
	public String getRes(){
		HttpServletRequest request=ServletActionContext.getRequest();
		try{
			EntityManagerFactory ef=Persistence.createEntityManagerFactory("mysql");
		    EntityManager em=ef.createEntityManager();
		    Query qu=em.createQuery("from persion order by userid");
		   
		    int count=qu.getResultList().size();
		    
		    Pageinfo pageinfo=new Pageinfo();
		    pageinfo.setCount(count);
		    String temp=request.getParameter("curpage");
		    if(temp!=null){
		    	pageinfo.setCurpage(Integer.parseInt(temp));
		    }
		   
            List list=qu.setFirstResult((pageinfo.getCurpage()-1)*pageinfo.getPagesize())
		                .setMaxResults(pageinfo.getPagesize())
		                .getResultList();
			
            request.setAttribute("pageinfo", pageinfo);
            request.setAttribute("list",list);
		}catch(Exception e){
			e.printStackTrace();
		}
		return "Today";
	
		
	}
}

Pageinfo代码:

 

package com.china.page;

public class Pageinfo {
    int count;   //总记录条数
    int pagesize=10;  //每页有几条
	int pagecount; //总共有几页 
	int curpage=1;
	
    public int getCurpage() {
		return curpage;
	}

	public void setCurpage(int curpage) {
		this.curpage = curpage;
	}

	public int getPagesize() {
		return pagesize;
	}

	public void setPagesize(int pagesize) {
		this.pagesize = pagesize;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}
	
	public int getPagecount() {
	    if(count%pagesize==0){
	    	pagecount=count/pagesize;
	    }else{
	    	pagecount=count/pagesize+1;
	    }
		return pagecount;
	}

	public void setPagecount(int pagecount) {
		this.pagecount = pagecount;
	}
	
}

 

 

自定义标签类com.china.page.taglibpage的代码:

package com.china.page;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import javax.servlet.jsp.tagext.TagSupport;

public class taglibpage extends TagSupport{    //要继承类TagSupport通过覆盖它的方法来实现
	
	private String formid;
	private Pageinfo pageinfo;
	
	public String getFormid() {
		return formid;
	}

	public void setFormid(String formid) {
		this.formid = formid;
	}

	public Pageinfo getPageinfo() {
		return pageinfo;
	}

	public void setPageinfo(Pageinfo pageinfo) {
		this.pageinfo = pageinfo;
	}



	@Override
	public int doStartTag() throws JspException {
		try {
			HttpServletRequest request=(HttpServletRequest) pageContext.getRequest();//pageContext是继承的类TagSupport的属性
			pageinfo=(Pageinfo) request.getAttribute("pageinfo"); 
			int curpage=pageinfo.getCurpage();
			int lastpage=pageinfo.getPagecount();
			
			int nextpage=curpage+1;
			int previouspage=curpage-1;

            JspWriter pw=pageContext.getOut();   //不要用PringWriter,要用JspWriter,否则无法控制其位置
            if(curpage==1){
            	pw.print(firstpage());
    			pw.print("<label  style='font-size:12px;color:#000000'>首页</label>&nbsp;");
    			pw.println(previouspage(previouspage));		
    			pw.print("<label  style='font-size:12px;color:#000000'>上一页</label>&nbsp;");
            }else{
            	pw.print(firstpage());
    			pw.print("<a href='javascript:firstpage()' style='font-size:12px;color:#000000'>首页</a>&nbsp;");
    			pw.println(previouspage(previouspage));		
    			pw.print("<a href='javascript:previouspage()' style='font-size:12px;color:#000000'>上一页</a>&nbsp;");
            }
			if(curpage==lastpage){
				pw.println(nextpage(nextpage));		
				pw.print("<label style='font-size:12px;color:#000000'>下一页</label>&nbsp;");
			    pw.print(lastpage(lastpage));
				pw.print("<label style='font-size:12px;color:#000000'>尾页</label>&nbsp;");
			}else{
				pw.println(nextpage(nextpage));		
				pw.print("<a  href='javascript:nextpage()' style='font-size:12px;color:#000000'>下一页</a>&nbsp;");
			    pw.print(lastpage(lastpage));
				pw.print("<a  href='javascript:lastpage()' style='font-size:12px;color:#000000'>尾页</a>&nbsp;");
			}

			pw.print("&nbsp;");
			pw.print("<span style='font-size:12px;color:#000000'>");
			pw.print("[");
			pw.print(curpage);
			pw.print("/");
			pw.print(pageinfo.getPagecount());
			pw.print("]");
			pw.print("&nbsp;");
			pw.print("共");
			pw.print(pageinfo.getCount());
			pw.print("条");
			pw.print("</span>");
			
		} catch (IOException e) {
		
			e.printStackTrace();
		}
	 // return SKIP_BODY;               //跳过开始和结束标签之间的代码。
	   return EVAL_BODY_INCLUDE;        //将body的内容输出到存在的输出流中,包括是jsp代码,也可以被输出
	}
	
	  /**
     * 首页
     * @return
     */
	public String firstpage(){
		StringBuffer sb=new StringBuffer();
		sb.append("<SCRIPT type='text/javascript'>");
		sb.append(" function firstpage(){");
		sb.append(" var theform=document.getElementById('");
		sb.append(this.formid);
		sb.append("');");
	    sb.append(" theform.action=theform.action+'?curpage=1'; ");
       sb.append(" document.location.href=theform.action;");	
		sb.append("}");
		sb.append("</SCRIPT>");
		
		return sb.toString();
	}
	
	/**
	 * 上一页
	 * @param previouspage
	 * @return
	 */
	public String previouspage(int previouspage){
		StringBuffer sb=new StringBuffer();
		sb.append("<SCRIPT type='text/javascript'>");
		sb.append(" function previouspage(){");
		sb.append(" var theform=document.getElementById('");
		sb.append(this.formid);
		sb.append("');");
		sb.append(" theform.action=theform.action+'?curpage=").append(previouspage+"';");
        sb.append(" document.location.href=theform.action;");	
		sb.append("}");
		sb.append("</SCRIPT>");
		return sb.toString();
	}
	
	/**
	 * 下一页
	 * @param nextpage
	 * @return
	 */
	public String nextpage(int nextpage){
		StringBuffer sb=new StringBuffer();
		sb.append("<SCRIPT type='text/javascript'>");
		sb.append(" function nextpage(){");
		sb.append(" var theform=document.getElementById('");
		sb.append(this.formid);
		sb.append("');");
		sb.append(" theform.action=theform.action+'?curpage=").append(nextpage+"';");
        sb.append(" document.location.href=theform.action;");	
		sb.append("}");
		sb.append("</SCRIPT>");
		return sb.toString();
	}
   
	/**
	 * 尾页
	 * @param lastpage
	 * @return
	 */
	public String lastpage(int lastpage){
		StringBuffer sb=new StringBuffer();
		sb.append("<SCRIPT type='text/javascript'>\n");
		sb.append(" function lastpage(){");
		sb.append(" var theform=document.getElementById('");
		sb.append(this.formid);
		sb.append("');");
	    sb.append(" theform.action=theform.action+'?curpage=").append(lastpage+"';");
        sb.append(" document.location.href=theform.action;");	
		sb.append("}\n");
		sb.append("</SCRIPT>");
		
		return sb.toString();
	}
	


}

显示分页的界面abc.jsp代码为:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<%@taglib prefix="lpm" uri="/tags/lpm" %>
<%
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 'abc.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">
	-->

</head>
  
  <body>
  <form action="<%=basePath%>lpm/step.action" id="fmcc">
  <table style="border:1px solid black">
     <thead>
        <tr style="border:1px solid black">
        <th>用户编号</th><th>用户名</th>
        </tr>
     </thead>  
     <tbody>
       <s:iterator value="#request.list" var="p">
        <tr style="border:1px solid black">
        <td><s:property value="#p.userid"/></td>
        <td><s:property value="#p.name"/></td>
        </tr>
       </s:iterator>
     </tbody>
  </table>
  </form>
  
  <div align="left">
    <lpm:mytaglib formid="fmcc" ></lpm:mytaglib>
  </div>
  </body>
</html>

 

 

 

 model层Persion实体类代码为:

 

package com.china.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="persion")
public class persion {
	  private Integer userid;
	  private String name;
   
	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	public Integer getUserid() {
		return userid;
	}
	public void setUserid(Integer userid) {
		this.userid = userid;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
  
}

 persistence.xml代码:

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
    
	<persistence-unit name="mysql" transaction-type="RESOURCE_LOCAL">
		<provider>org.hibernate.ejb.HibernatePersistence</provider>
		   <jta-data-source>java:comp/env/jdbc/mysql</jta-data-source>
		  
		  
		   <class>com.china.model.persion</class>
		
		
		
	</persistence-unit>
  
</persistence>

tomcat中server.xml配置信息:

  <Context path="/pageTest" docBase="/pageTest"  reloadable="false" crossContext="true">		 
		<Resource name="jdbc/mysql"   auth="Container"  type="javax.sql.DataSource"  
		maxActive="5"   maxIdle="2"   maxWait="10000"   removeAbandoned="true" removeAbandonedTimeout="60" logAbandoned="true" 
		driverClassName="com.mysql.jdbc.Driver" 
		url="jdbc:mysql://localhost/lpm?user=root&amp;password=" /> 
 </Context>

  

你可能感兴趣的:(Hibernate)