基于XML的struts2分页组件

基于XML的struts2分页组件:
1、自定义JSP标签
import java.io.File;
import java.io.IOException;
import java.net.URL;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.sitech.res.util.LogHelper;

public class PageTag extends TagSupport
{
    private static final long serialVersionUID = 8417047654596701521L;

    private String pageInfoUrl;

    private String hiddenProperty;

    // single,multiple
    private String selectMode = "single";

    private String target = "pageResult";

    public void setTarget(String target)
    {
        this.target = target;
    }

    public void setPageInfoUrl(String pageInfoUrl)
    {
        this.pageInfoUrl = pageInfoUrl;
    }

    public String getHiddenProperty()
    {
        return hiddenProperty;
    }

    public void setHiddenProperty(String hiddenProperty)
    {
        this.hiddenProperty = hiddenProperty;
    }

    public String getSelectMode()
    {
        return selectMode;
    }

    public void setSelectMode(String selectMode)
    {
        this.selectMode = selectMode;
    }

    public int doStartTag() throws JspException
    {
        StringBuffer str = new StringBuffer("<div id='").append(target).append(
                "'><div class='sortlist'>");
        try
        {
            str.append("<div class='tableheadbg'>查询结果列表<span class='darkblue'></span></div>");
            str.append("<table width='100%' border='0' cellpadding='0' cellspacing='0'>");
            int titleLength = 0;
            StringBuffer readMethodS = new StringBuffer("");
            StringBuffer tableHeadS = new StringBuffer("");
            String pageDataType = null;
            str.append("<thead><tr class='columnheading'>");
            try
            {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();

                ClassLoader loader = this.getClass().getClassLoader();
                URL url = loader.getResource(pageInfoUrl);
                File file = new File(url.getPath());

                Document doc = db.parse(file);
                Element root = doc.getDocumentElement();

                pageDataType = root.getAttribute("pageDataType");

                NodeList nl = root.getElementsByTagName("attribute");
                titleLength = nl.getLength();
                Element element = null;
                String[] hidPros = null;
                int hidProsLen = 0;
                if (hiddenProperty != null)
                {
                    hidPros = hiddenProperty.split(",");
                    hidProsLen = hidPros.length;
                }
                String tableHead = null;
                outter: for (int i = 0; i < titleLength; i++)
                {
                    element = (Element) nl.item(i);
                    String readMethod = element.getAttribute("readMethod");
                    String hid = "";
                    for (int j = 0; j < hidProsLen; j++)
                    {
                        hid = hidPros[j];
                        if (hid.equals(readMethod))
                        {
                            continue outter;
                        }
                    }
                    tableHead = element.getAttribute("displayName");
                    readMethodS.append(readMethod);
                    tableHeadS.append(tableHead);
                    if (i != titleLength - 1)
                    {
                        readMethodS.append(",");
                        tableHeadS.append(",");
                    }
                    str.append("<th class='tabletd header'>").append(tableHead).append("</th>");
                }
            }
            catch (Exception e)
            {
                LogHelper.logExceptionStackTrace(e);
            }
            str
                    .append(
                            "</tr></thead><tbody><tr class='tablewhitebg'><td class='tabletd' colspan='")
                    .append(titleLength)
                    .append("'><div align='center'><b>没有记录</b></div></td></tr>");
            str
                    .append(
                            "</tbody></table></div></div><input type='hidden' name='readMethodS' id='readMethodS' value='")
                    .append(readMethodS).append("'/>").append(
                            "<input type='hidden' name='tableHeadS' id='tableHeadS' value='")
                    .append(tableHeadS).append("'/>").append(
                            "<input type='hidden' name='pageDataType' id='pageDataType' value='")
                    .append(pageDataType).append("'/>").append(
                            "<input type='hidden' name='selectMode' id='selectMode' value='")
                    .append(selectMode).append("'/>");
            ;
            this.pageContext.getOut().write(str.toString());
        }
        catch (IOException e)
        {
            throw new JspException("分页标签开始异常", e);
        }
        return EVAL_BODY_INCLUDE;
    }

    public int doEndTag() throws JspException
    {
        StringBuffer str = new StringBuffer("");
        try
        {
            str
                    .append(
                            "<table width='100%' class='footer_table'><tr><td class='footer' align='right'>共<label id='rowCountText'></label>&nbsp;条记录|&nbsp;&nbsp;")
                    .append("<input type='hidden' id='rowCount'/>")
                    .append("每页&nbsp;")
                    .append(
                            "<select id='pageSize' name='page.pageSize'><option value='10'>&nbsp;10</option><option value='20'>&nbsp;20</option><option value='50'>&nbsp;50</option><option value='100'>100</option><option value='200'>200</option></select>")
                    .append("&nbsp;条记录|&nbsp;&nbsp;")

                    .append("共<label id='pageSumText'></label>&nbsp;页|&nbsp;&nbsp;")
                    .append("<input type='hidden' id='pageSum'/>")
                    .append("<input type='hidden' name='pageInfoUrl' id='pageInfoUrl' value='")
                    .append(pageInfoUrl)
                    .append("'/>")
                    .append(
                            "<input type='hidden' name='hiddenProperty' id='hiddenProperty' value='")
                    .append(hiddenProperty)
                    .append("'/>")
                    .append(
                            "<input type='submit' value='首页' onclick='pageBegin()'  class='buttonStyle2'/>")
                    .append(
                            "<input type='submit' value='上一页' onclick='pageBefore()' class='buttonStyle2'/>")
                    .append("第")
                    .append(
                            "<input type='text' name='page.pageNo' id='pageNo' value='1' size='3'/>")
                    .append("页")
                    .append(
                            "<input type='submit' value='下一页' onclick='pageNext()' class='buttonStyle2'/>")
                    .append(
                            "<input type='submit' value='末页' onclick='pageLast()' class='buttonStyle2'/>&nbsp;&nbsp;&nbsp;</div></td></tr></table>");
            this.pageContext.getOut().write(str.toString());
        }
        catch (IOException e)
        {
            throw new JspException("分页标签结束异常", e);
        }
        return (EVAL_PAGE);

    }

    public void release()
    {
    }
}

2、自定义标签配置文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/j2ee/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
	<tlib-version>1.0</tlib-version>
	<jsp-version>1.2</jsp-version>
	<short-name>app</short-name>

	<tag>
		<name>pageTag</name>
		<tag-class>com.sitech.res.util.tag.PageTag</tag-class>
		<body-content>jsp</body-content>
		<attribute>
			<name>pageInfoUrl</name>
			<required>true</required>
		</attribute>
		<attribute>
			<name>selectMode</name>
			<required>false</required>
		</attribute>
		<attribute>
			<name>hiddenProperty</name>
			<required>false</required>
		</attribute>
		<attribute>
			<name>target</name>
			<required>false</required>
		</attribute>
	</tag>
</taglib>

修改web.xml
<jsp-config>
		<taglib>
			<taglib-uri>/si_page</taglib-uri>
			<taglib-location>/WEB-INF/tld/si_page.tld</taglib-location>
		</taglib>
	</jsp-config>

3、JSP查询页面
<p:pageTag pageInfoUrl="resource/config/page/s0230/VirtNet.xml"
		target="pageResult">

4、查询结果展示配置文件VirtNet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beaninfo>
    <attribute readMethod="getVirtNetId" displayName="虚拟网编码" />

	<attribute readMethod="getVirtNetName" displayName="虚拟网名称" />

	<attribute readMethod="getVirtNet" displayName="虚拟网号码" />
	
	<attribute readMethod="getAreaId" displayName="服务区" />	
	
	<attribute readMethod="getNbrHeadId" displayName="局向" />
	
</beaninfo>

5、查询结果JSP页面
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="p" uri="/si_page"%>
<%@page import="java.util.List"%>
<%@page import="java.lang.reflect.Method"%>
<%@page import="com.sitech.res.util.page.Page"%>
<html>
<head>
<title>分页页面</title>
<link href="nresources/default/css/style.css" rel="stylesheet"
	type="text/css">
<link href="nresources/default/css/portalet.css" rel="stylesheet"
	type="text/css">
<script type="text/javascript" src="njs/jquery/jquery_tableSort.js"></script>
<script type="text/javascript" src="njs/jquery/listColor.js"></script>
<script type="text/javascript" src="njs/jquery/folding.js"></script>
</head>
<%
String[] methodName = (String[])request.getAttribute("methodName");
Page pageBean = (Page)request.getAttribute("page");
List<Object> resultList = ((Page)request.getAttribute("page")).getList();
%>
<body>
<div class="sortlist">
<div class="tableheadbg">查询结果列表<span class="darkblue"></span></div>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
	<thead>
		<tr class="columnheading">
			<s:if test="#request.selectMode == 'single'">
				<th>选择</th>
			</s:if>
			<s:elseif test="#request.selectMode == 'multiple'">
				<th><input type="checkbox"
					id="selectAll" onclick="selectAllHandler(this,'selectRowId')" />全选</th>
			</s:elseif>
			<s:iterator value="#request.tableHead" var="tableHead">
				<th class="tabletd header"><s:property value="tableHead" /></th>
			</s:iterator>
		</tr>
	</thead>
	<tbody>
		<%
		if(resultList == null || resultList.size() <= 0 )
		{
		%>
		<tr class="tablewhitebg">
			<td class='tabletd' colspan='<%=methodName.length+1 %>'>
			<div align='center'><b>没有记录</b></div>
			</td>
		</tr>
		<%    
		}
		else
		{
	        Method method = null;
			for(Object object : resultList)
			{
			    String objectIdMethod = "get"+object.getClass().getSimpleName()+"Id";
			    Object objectId = object.getClass().getMethod(objectIdMethod).invoke(object);
			%>
		<tr class="tablewhitebg" onclick="trClickHandler(this)"
			ondblclick="trDoubleClickHandler(this)" id="<%=objectId %>">
			<s:if test="#request.selectMode == 'single'">
				<td class="tabletd"><input type="radio" name="selectRowId"
					value="<%=objectId %>" /></td>
			</s:if>
			<s:elseif test="#request.selectMode == 'multiple'">
				<td class="tabletd"><input type="checkbox" name="selectRowId"
					value="<%=objectId %>" /></td>
			</s:elseif>
			<%
				    for(String getMethodName : methodName)
				    {
				        method = object.getClass().getMethod(getMethodName);	
				        Object res = method.invoke(object);
				        if(res == null)
				        {
				            res = "";
				        }
					    out.println("<td class='tabletd'>"+res.toString()+"</td>");
					}
					%>
		</tr>
		<%
			}
		}		
		%>
	</tbody>
</table>
</div>
</body>
</html>
<%
String rowCount = (String)request.getAttribute("page.rowCount");
String pageSum = (String)request.getAttribute("page.pageSum");
%>
<script type="text/javascript">
<!--
$(document).ready(function() {
	$("#rowCountText").text('<%=rowCount%>');	
	$("#pageSumText").text('<%=pageSum%>');
	document.getElementById('rowCount').value = "<s:property value='page.rowCount'/>";	
	document.getElementById('pageSum').value="<s:property value='page.pageSum'/>";	
	document.getElementById('pageSize').value = "<s:property value='page.pageSize'/>";	
	document.getElementById('pageNo').value="<s:property value='page.pageNo'/>";	
});
//-->
</script>

分页js文件page.js
function getSingleSelect()
{
	var temp = document.getElementsByName("selectRowId");
	for (var i = 0, length = temp.length; i < length; i++) 
	{   
	    if (temp[i].checked) 
	    {   
		    return temp[i].value;   
		}   
	}  

}

function getMultipleSelect()
{
	var temp = document.getElementsByName("selectRowId");
	var selectStr;
	for (var i = 0, length = temp.length; i < length; i++) 
	{   
	    if (temp[i].checked) 
	    {   
	    	if(selectStr==""||selectStr==null)
	    	{
	    		selectStr = temp[i].value;
	    	}
	    	else if(selectStr!="")
	    	{
	    		selectStr = temp[i].value+','+selectStr;
	    	}
		}   
	}
	return selectStr;   
}

function selectAllHandler(selectAll, checkBoxName)
{
	$("input[name='"+checkBoxName+"']").attr("checked", selectAll.checked);
}
function queryPage() 
{
	pageBegin();
}

function pageBegin() 
{
	document.getElementById('pageNo').value = 1;
	return false;
}

function pageBefore() 
{
	var pageNo = document.getElementById('pageNo').value;
	if (pageNo && parseInt(pageNo) > 1) 
	{
		document.getElementById('pageNo').value = parseInt(pageNo) - 1;
	}
	return false;
}

function pageNext() 
{
	var pageNo = document.getElementById('pageNo').value;
	var pageSum = document.getElementById('pageSum').value;
	if (pageNo && parseInt(pageNo) < pageSum) 
	{
		document.getElementById('pageNo').value = parseInt(pageNo) + 1;
	}
	return false;
}

function pageLast() 
{
	document.getElementById('pageNo').value = document
			.getElementById('pageSum').value;
	return false;
}

function trDoubleClickHandler(selectTr)
{	
	try 
	{
		if (typeof (eval(dbClickCallBackHandler)) == "function" && selectTr) 
		{
		    
			dbClickCallBackHandler(selectTr.id);
		}
	}
	catch (e) 
	{
	}
}

function trClickHandler(selectTr)
{
	var doc = $(selectTr).find("input[name='selectRowId']");
	if(doc)
	{
		doc.attr("checked", !doc.attr("checked"));
	}
}

你可能感兴趣的:(java,xml,jsp,Web,servlet)