spring+hibernate+struts2 annotation实现分页(3)

这几天写了个ssh2分页实现,放到博客里留个记号,先贴代码有空再写说明了

struts2自定义标签实现
package com.xangqun.tag;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.components.Component;
import org.apache.struts2.views.jsp.ComponentTagSupport;

import com.opensymphony.xwork2.util.ValueStack;

public class PageStruts2Tag extends ComponentTagSupport{

	private static final long serialVersionUID = 1L;
	
    private int totalPage; //总页数
	
	private int currentPage; //当前页
	
    private int totalCount;  //总数
    
    private int displayNum=10;    //页面显示的页数
    
    private boolean isDisplaySelect= true;  //是否显示选择框
    
    private boolean isDisplayGoToPage= false; //是否显示输入框
    
    private String style="infoPage"; //样式id
    
	@Override
	public Component getBean(ValueStack stack, HttpServletRequest req,
			HttpServletResponse res) {
	   return new PageStrutsTwo(stack);
	}
	
	@Override
	protected void populateParams() {
		super.populateParams();
		PageStrutsTwo pst=(PageStrutsTwo)component;
		pst.setCurrentPage(currentPage);
		pst.setDisplayGoToPage(isDisplayGoToPage);
		pst.setDisplayNum(displayNum);
		pst.setDisplaySelect(isDisplaySelect);
		pst.setTotalCount(totalCount);
		pst.setTotalPage(totalPage);
		pst.setStyle(style); 
	}

	public void setTotalPage(int totalPage) {
		this.totalPage = totalPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public void setDisplayNum(int displayNum) {
		this.displayNum = displayNum;
	}

	public void setDisplaySelect(boolean isDisplaySelect) {
		this.isDisplaySelect = isDisplaySelect;
	}

	public void setDisplayGoToPage(boolean isDisplayGoToPage) {
		this.isDisplayGoToPage = isDisplayGoToPage;
	}

	public void setStyle(String style) {
		this.style = style;
	}
	
}

package com.xangqun.tag;

import java.io.Writer;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.components.Component;

import com.opensymphony.xwork2.util.ValueStack;

public class PageStrutsTwo extends Component {
	
    private int totalPage; //总页数
	
	private int currentPage; //当前页
	
    private int totalCount;  //总数
    
    private int displayNum=10;   //页面显示的页数
    
    private boolean isDisplaySelect= true; //是否显示选择框
    
    private boolean isDisplayGoToPage= false; //是否显示输入框
    
    private String style="infoPage"; //样式id
    
	public PageStrutsTwo(ValueStack stack) {
		super(stack);
	}

	@Override
	public boolean start(Writer writer) {
		boolean result = super.start(writer);   
		try{
			StringBuilder str=new StringBuilder(1024);
			String cleanUrl=getCleanUrl();
			boolean isValid=true;
			isValid =(this.getStack().findValue(String.valueOf(totalPage))== null && this.getStack().findValue(String.valueOf(totalCount))== null) ? false : true;
			if (isValid) { 
				str.append("<div id='").append(style).append("'><ul>");
		        if (currentPage > 1) {
		        	str.append("<li><a href='" + getCompleteUrl(cleanUrl, currentPage - 1) +
				              "' class='upPage' title='上一页'></a></li>");
				} else {
					str.append("<li><a class='upPage' title='目前已是第一页'></a></li>");
				}
				
		        if (displayNum == 0) {
		        	str.append("<li class='pages'><span class='currentPage'>" + currentPage + "</span>/" + totalPage + "</li>");
		          } else {
		            int pagenumber = displayNum;
		            int pagecenter = pagenumber / 2 - 1;
		            int pagebet = pagenumber / 2 + 1;
		            int beginPage = 1;
		            int endPage = 1;

		            if (currentPage < pagebet) {
		              beginPage = 1;
		            } else {
		              beginPage = currentPage - pagecenter;
		            }

		            if (currentPage + pagecenter > totalPage) {
		              endPage = totalPage;
		            } else {
		              endPage = currentPage + pagecenter;
		            }

		            if (currentPage + pagecenter < pagenumber) {
		              endPage = pagenumber;
		            }

		            if (endPage - currentPage < pagecenter) {
		              beginPage = totalPage - (pagenumber - 1);
		              if (beginPage != 1) {
		                beginPage += 1;
		              }
		            }

		            if (beginPage <= 0) {
		              beginPage = 1;
		            }

		            if (endPage > totalPage) {
		              endPage = totalPage;
		            }

		            if (currentPage >= pagebet && beginPage != 1) {
		            	str.append("<li><a href='" + getCompleteUrl(cleanUrl, 1) +
		                      "' class='everyPage'>1</a></li>");
		              if (currentPage != pagebet) {
		            	  str.append("<li>...&nbsp;</li>");
		              }
		            }

		            for (int i = beginPage; i <= endPage; i++) {

		              StringBuilder item=new StringBuilder(1024);
		              if (i != currentPage) {
		                item.append("<li><a href='" + getCompleteUrl(cleanUrl, i) +
		                        "' class='everyPage'>" + i +
		                        "</a></li>");
		              } else {
		                item.append("<li><a class='nowPage'>" + i +
		                        "</a></li>");
		              }
		              str.append(item);
		            }
		          }
		          if (currentPage < totalPage) {
		        	  str.append("<li><a href='" + getCompleteUrl(cleanUrl, currentPage + 1) +
		                    "' class='downPage' title='下一页'></a></li>");
		          } else {
		        	  str.append("<li><a class='downPage' title='目前已是最后一页'></a></li>");
		          }

		          boolean isSelect = isDisplaySelect;
		          if (isDisplayGoToPage) {
		            isSelect = false;
		            str.append("<li>&nbsp;&nbsp;到第&nbsp;<input id='inputPage' value='" + currentPage + "'/>&nbsp;页</li>");
		            StringBuilder script =new StringBuilder("javascript:var goPage=this.parentNode.parentNode.getElementsByTagName('input')[0].value;if(isNaN(goPage)||goPage>"
		            + totalPage + "||goPage<1||goPage==" + currentPage + ")return;document.location='" + getCompleteUrlNoParam(cleanUrl)
		            + "page='+goPage;return false;");
		            str.append("<li><a href='javascript:;' onclick=\"" + script + "\" class='goToPage'></a></li>");
		          }

		          if (isSelect) {
		        	  str.append("<li>&nbsp;&nbsp;到第&nbsp;<select name='select2' onchange=\"window.location.href='" +
		                    getCompleteUrlNoParam(cleanUrl) +
		                    "page='+this.options[this.selectedIndex].value + ''\">");
		            for (int iCount = 1; iCount <= totalPage; iCount++) {
		              String strSelected = "";
		              if (iCount == currentPage) {
		                strSelected = "selected";
		              }
		              str.append("<option value='" + iCount + "' " + strSelected + ">-" +
		                      iCount + "-</option>");
		            }
		            str.append("</select>&nbsp;页</li>");
		          }
		          str.append("</ul></div>");
			}
			 writer.write(str.toString());
			 
		}catch (Exception e) {
		}
		
		return result;
	}

	private String getCompleteUrlNoParam(String reqUrl) {
      if (reqUrl.indexOf("?") > 0) {
        return reqUrl + "&";
      } else {
        return reqUrl + "?";
      }
    }

	private String getCompleteUrl(String reqUrl, int page) {
       if (reqUrl.indexOf("?") > 0) {
         return reqUrl + "&page=" + page;
       } else {
        return reqUrl + "?page=" + page;
       }
    }

	private String getCleanUrl() throws Exception {
		HttpServletRequest request=(HttpServletRequest)ServletActionContext.getRequest();
		Map parameters=request.getParameterMap();
		boolean isFirst=true;
		Set entries=parameters.entrySet();
		Iterator it=entries.iterator();
		//TODO
		//这里的方法可以根据需要修改下
		String reqUrl=(String)request.getAttribute("struts.request_uri");
		HttpServletResponse response=(HttpServletResponse)ServletActionContext.getResponse();
		
		while(it.hasNext()){
			Map.Entry entry = (Map.Entry) it.next();
		    String Name = (String) entry.getKey();
		    String[] Value = (String[]) entry.getValue();
		    String[] temp = new String[Value.length];
		    for (int i = 0; i < Value.length; i++) {
		        temp[i] = Value[i];
		    }
		    
		    for (int i = 0; i < Value.length; i++) {
		        temp[i] = URLEncoder.encode(temp[i], "GBK");
		    }
		    if (Name.equalsIgnoreCase("page") == false) {
		        for (int j = 0; j < temp.length; j++) {
		          if (temp[j]!=null||temp[j]!="") {
		            if (isFirst) {
		              isFirst = false;
		              reqUrl += "?" + Name + "=" + temp[j];
		            } else {
		              String param = "&" + Name + "=" + temp[j];
		              String param2 = "&" + Name + "=" + temp[j] + "&";
		              if (reqUrl.indexOf(param2) < 0) {
		                if (reqUrl.endsWith(param) == false) {
		                  reqUrl += "&" + param;
		                }
		              }
		            }
		          }
		        }
		      }
		}
		return response.encodeURL(reqUrl);
	}

	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;
	}
	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}
	public int getDisplayNum() {
		return displayNum;
	}

	public void setDisplayNum(int displayNum) {
		this.displayNum = displayNum;
	}
	public boolean isDisplaySelect() {
		return isDisplaySelect;
	}

	public void setDisplaySelect(boolean isDisplaySelect) {
		this.isDisplaySelect = isDisplaySelect;
	}
	public boolean isDisplayGoToPage() {
		return isDisplayGoToPage;
	}

	public void setDisplayGoToPage(boolean isDisplayGoToPage) {
		this.isDisplayGoToPage = isDisplayGoToPage;
	}
	public String getStyle() {
		return style;
	}

	public void setStyle(String style) {
		this.style = style;
	}
	
}

在WEB-INF目录下新建一个tlds目录,PageTags.tld放置在tlds目录里
PageTags.tld
<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE taglib
        PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
        "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
    <tlib-version>1.0</tlib-version>
    <jsp-version>1.2</jsp-version>
    <short-name>pageTags</short-name>
    <uri>/PageTags</uri>
    <display-name>pageTags</display-name>
    <description></description>
    <tag>
     <name>PageStruts2Tag</name>
     <tag-class>com.xangqun.tag.PageStruts2Tag</tag-class>
     <body-content>JSP</body-content>
     <display-name>pageStruts2Tag</display-name>
	      <attribute>
            <name>totalPage</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
            <type>int</type>
        </attribute>
        <attribute>
            <name>currentPage</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
            <type>int</type>
        </attribute>
        <attribute>
            <name>style</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
            <type>java.lang.String</type>
        </attribute>
        <attribute>
            <name>totalCount</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
            <type>java.lang.String</type>
        </attribute>
         <attribute>
            <name>displayNum</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
            <type>int</type>
        </attribute>
        <attribute>
            <name>isDisplaySelect</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
            <type>boolean</type>
        </attribute>
        <attribute>
            <name>isDisplayGoToPage</name>
            <required>false</required>
            <rtexprvalue>true</rtexprvalue>
            <type>boolean</type>
        </attribute>
    </tag>
</taglib>    

css样式自己写个就可以
<%@ page language="java" contentType="text/html; charset=gbk"
	pageEncoding="gbk"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<%@ taglib uri="/PageTags" prefix="pageTags"%>
<!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=gbk">
<title>demo</title>
<link rel="stylesheet" type="text/css" href="css/page.css" />
</head>
<body>
<s:iterator value="pagination.list" var="p">
   ${p.name}
</s:iterator>
<pageTags:PageStruts2Tag currentPage="${pagination.currentPage}" totalPage="${pagination.totalPage}" totalCount="${pagination.totalCount}" displayNum="6" />
</body>
</html>

效果看附件(点击看原图)

你可能感兴趣的:(java,spring,Hibernate,servlet,struts)