分页 自定义控件 spring

先看效果  样式 可以 css 修改 各自 适合 的样式 

 

代码下载位置 :http://download.csdn.net/download/knight_black_bob/8767507 

 

 

 

 前端效果<page:navigator type="frontPage">
分页 自定义控件 spring_第1张图片
 

 后台效果<page:navigator type="backPage">
分页 自定义控件 spring_第2张图片
 <page:navigator type="defaultPage">
分页 自定义控件 spring_第3张图片
 

 

 

 

 

 

效果 看完后,看结构


分页 自定义控件 spring_第4张图片
 

 

 

初始化数据

package baoyou.bean;
import java.util.ArrayList;
import java.util.List;
public class UserPool {

	private static List<User> userList =new ArrayList<User>();
	
	static {
		for (int i = 0; i < 100; i++) {
			User user  = new  User();
			user.setUserId(i);
			user.setUserName("user"+i);
			user.setPassword("user"+i);
			userList.add(user);
		}
	}
	
	
	private static UserPool instance;  
    private UserPool(){  }
    public static synchronized UserPool getInstance() {  
        if (instance == null) {  
            instance = new UserPool();  
        }  
        return instance; 
     }
	
    public   List<User> getUserList() {
		return userList;
	}
    
    public   int getCount() {
		return userList.size();
	}
    
    //limit #{start},#{pageSize}
    public List<User> getUserList(PageBean pb) {
    	 List<User>  list = new ArrayList<User>(); 
    	 for (int i = 0; i < userList.size(); i++) {
		    	if ( pb.getStart() >= 0  &&  i >=  pb.getStart()   && i<  pb.getStart() + pb.getPageSize()  ) {
		    	list.add(  userList.get(i) ) ;
				}
		 }
    	 return list ;
	}
    
}

 

User

package baoyou.bean;

public class User {

	private int userId;
	private String userName;
	private String password;
	
	
	
	public int getUserId() {
		return userId;
	}
	public void setUserId(int userId) {
		this.userId = userId;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
	
}

 

 

page/ NavigatorTag

package baoyou.page;


import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
 

import java.io.IOException;

/**
 * 显示导航条,可利用此改变每页的记录数,上下翻页和跳页 使用方法:<page:navigator type='BUTTON'/>
 * 
 * @author Satan
 */
@SuppressWarnings("serial")
public class NavigatorTag extends TagSupport {
	/** 导航条的类型(BUTTON/TEXT)(按钮型/文字链接型) */
	private String type = "Page"; // 选择导航条类型默认"BUTTON"(BUTTON/TEXT)

	public void setType(String newType) {
		type = newType;
	}

	public int doStartTag() throws JspException {
		try {
			String bar = getNavigatorBar(type);
			pageContext.getOut().write(bar);
			return SKIP_BODY;
		} catch (IOException ioe) {
			throw new JspException(ioe.getMessage());
		}
	}

	public int doEndTag() throws JspException {

		return EVAL_PAGE;

	}

	/**
	 * 根据指定类型获得导航条预先设计的导航条
	 * 
	 * @param type
	 *            导航条类型(BUTTON/TEXT)
	 * @return 返回导航条的HTML代码,若指定类型不存在,返回""
	 */

	private String getNavigatorBar(String type) {
		String bar = "";
		String pageNo = ((Integer) pageContext.getAttribute("pageNo")).toString();//第几页
		String pages = ((Integer) pageContext.getAttribute("pages")).toString();//总页数
		String total = ((Integer) pageContext.getAttribute("total")).toString();//总条数
		String pageSize = ((Integer) pageContext.getAttribute("pageSize"))
				.toString();
		String nextDisabled = "";
		String prevDisabled = "";
		if (Integer.parseInt(pageNo) >= Integer.parseInt(pages))
			nextDisabled = "disabled";
		if (Integer.parseInt(pageNo) <= 1)
			prevDisabled = "disabled";
		String pageSizeInput = pageSize;
		String firstText = "<span style='color:#777;'>首  页</span>";
		String prevText = "<span  style='color:#777;'>上一页</span>";
		String nextText = "<span  style='color:#777;'>下一页</span>";
		String lastText = "<span  style='color:#777;'>最后一页</span>";
		String nowPage = "<span  style='color:#777;'></span>";
		String pageNoInput = "<input type='text' maxlength='9' size='3' size='2' value='"
			+ pageNo
			+ "' "
			+ "onChange=\"javascript:this.form.pageNo.value=this.value\">";
		if (!type.equalsIgnoreCase("frontPage")) {
		if (type.equalsIgnoreCase("backPage")) {
			
			if (prevDisabled.equalsIgnoreCase("")) {
				firstText = "<span><a href='first' "
						+ "onClick=\"javascript:document.pager.choice.value='first';document.pager.submit();return false;\">"
						+ "首  页" + "</a></span>";
				prevText = "<span><a href='prev' "
						+ "onClick=\"javascript:document.pager.choice.value='prev';document.pager.submit();return false;\">"
						+ "上一页" + "</a></span>";
			}
			if (nextDisabled.equalsIgnoreCase("")) {
				nextText = "<span><a href='next' "
						+ "onClick=\"javascript:document.pager.choice.value='next';document.pager.submit();return false;\">"
						+ "下一页" + "</a></span>";
				lastText = "<span><a href='last' "
						+ "onClick=\"javascript:document.pager.choice.value='last';document.pager.submit();return false;\">"
						+ "最后一页" + "</a></span>";
			}
			bar = "每页pageSize条记录 | \n"
					+ "<span style='color:#777;'>共pages页/total条记录</span> | \n"
					+ "first \n prev \n next \n last \n | <span style='color:#777;'>第pageNo页</span>\n"
					+ " <input type='submit' value='go' onClick=\"javascript:this.form.choice.value='current';\">\n";
		}else if(type.equals("defaultPage")){
			if (prevDisabled.equalsIgnoreCase("")) {
				firstText = "<span><a href='first' "
						+ "onClick=\"javascript:document.pager.choice.value='first';document.pager.submit();return false;\">"
						+ "首  页" + "</a></span>";
				prevText = "<span><a href='prev' "
						+ "onClick=\"javascript:document.pager.choice.value='prev';document.pager.submit();return false;\">"
						+ "上一页" + "</a></span>";
			}
			if (nextDisabled.equalsIgnoreCase("")) {
				nextText = "<span><a href='next' "
						+ "onClick=\"javascript:document.pager.choice.value='next';document.pager.submit();return false;\">"
						+ "下一页" + "</a></span>";
				lastText = "<span><a href='last' "
						+ "onClick=\"javascript:document.pager.choice.value='last';document.pager.submit();return false;\">"
						+ "最后一页" + "</a></span>";
			}
			bar = "<span style=\"color:#777;text-decoration: none;\">每页pageSize条记录</span> | \n"
					+ "<span style=\"color:#777;\">共pages页/total条记录</span> | \n"
					+ "first \n prev \n next \n last \n <span style=\"color:#777;\">第pageNo页</span>\n ";
			pageNoInput=pageNo;
		
		}
			bar = StringUtil.replace(bar, "pageSize", pageSizeInput);
			bar = StringUtil.replace(bar, "pages", pages);
			bar = StringUtil.replace(bar, "total", total);
			bar = StringUtil.replace(bar, "first", firstText);
			bar = StringUtil.replace(bar, "prev", prevText);
			bar = StringUtil.replace(bar, "next", nextText);
			bar = StringUtil.replace(bar, "last", lastText);
			bar = StringUtil.replace(bar, "pageNo", pageNoInput);
			
		}else if (type.equalsIgnoreCase("frontPage")) {
			int i = 1;
			int totalPages = (Integer) pageContext.getAttribute("pages");
			int min = Integer.parseInt(pageNo) - 3;
			int max = Integer.parseInt(pageNo) + 3;
			if (min <= 1) {
				min = 1;
				max = min + 6;
			} else {
				if(Integer.parseInt(pageNo)  ==5){
					nowPage += "<span><a href='#' "
						+ "onClick=\"javascript:document.pager.pageNo.value="
						+ 1 + ";document.pager.submit();return false;\">" + 1
						+ "</a></span>";
				
				}
				else{
				nowPage += "<span><a href='#' "
						+ "onClick=\"javascript:document.pager.pageNo.value="
						+ 1 + ";document.pager.submit();return false;\">" + 1
						+ "</a></span>";
				nowPage += "<span>...</span>";
				}
			}
			if (max >= totalPages) {
				min = max - 6;
				max = totalPages;
			}
			for (i = min; i <= max; i++) {
				if (i >= 1 && i <= totalPages) {
					if (i == Integer.parseInt(pageNo)) {
						nowPage += "<span><a href='#' style='color:red'"
								+ "onClick=\"javascript:document.pager.pageNo.value="
								+ i
								+ ";document.pager.submit();return false;\">["
								+ i + "]</a></span>";
					} else {
						nowPage += "<span><a href='#' "
								+ "onClick=\"javascript:document.pager.pageNo.value="
								+ i
								+ ";document.pager.submit();return false;\">"
								+ i + "</a></span>";
					}
				}
			}
			if (max<totalPages) {
				if((totalPages - Integer.parseInt(pageNo))==4){
					nowPage += "<span><a href='#' "
						+ "onClick=\"javascript:document.pager.pageNo.value="
						+ totalPages
						+ ";document.pager.submit();return false;\">"
						+ totalPages + "</a></span>";
				}
				else{
				 nowPage += "<span>...</span>";
				 nowPage += "<span><a href='#' "
						+ "onClick=\"javascript:document.pager.pageNo.value="
						+ totalPages
						+ ";document.pager.submit();return false;\">"
						+ totalPages + "</a></span>";
				}
			}
			
			firstText = "<span><a href='#' "
				+ "onClick=\"javascript:document.pager.pageNo.value="+1+";document.pager.submit();return false;\">"
				+ "<span> &lt;&lt; </span>" + "</a></span>";
			
			lastText = "<span><a href='last' "
				+ "onClick=\"javascript:document.pager.pageNo.value="+totalPages+";document.pager.submit();return false;\">"
				+ "<span> &gt;&gt; </span>" + "</a></span>";
			
			bar ="first \n now \n last \n ";
			
			bar = StringUtil.replace(bar, "now", nowPage);
			bar = StringUtil.replace(bar, "first", firstText);
			bar = StringUtil.replace(bar, "last", lastText);
		}
		return bar.toString();
	}
}

 

 

page/ PagerTag

package baoyou.page;

import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.IOException;

/**
 * 分页框架标记 从表单中获得全部参数,予以保存并自动生成对应的<input type=hidden>表单
 * 通过计算当前的页号,操作,以及控制每页记录数,提供起始记录号,和每页显示记录数,
 * 供框架内的程序控制显示起始的记录位置和数量,若中途转出后返回,直接调用该页面即可 恢复原来转出时的情况.若页号超出范围,将自动调成最接近的合理值.
 * 使用举例:
 */
@SuppressWarnings("serial")
public class PagerTag extends BodyTagSupport {
	private StringBuffer output; // 保存输出
	private int pageNo; // 当前页面
	private int pageSize; // 每页记录数
	private int index = 0; // 起始记录数,缺省为0
	private int pages; // 总页数
	@SuppressWarnings("unused")
	private String queryString; // 保存分页信息和所需传递的其它变量值
	@SuppressWarnings("unused")
	private String prevPage; // 前一页的URL和queryString
	@SuppressWarnings("unused")
	private String nextPage; // 下一页的URL和queryString
	@SuppressWarnings("unused")
	private String currentPage; // 当前页的URL和queryString
	@SuppressWarnings("unused")
	private String firstPage; // 第一页的URL和queryString
	@SuppressWarnings("unused")
	private String lastPage; // 最后页的URL和queryString
	private boolean resume = false; // 是否是恢复操作
	private int total = 0; // 记录总数,即需要分页显示的记录总数,初始化默认为0
	private int defaultPageSize = 20; // 缺省每页记录数,可在导航条中改变每页记录数的值
	private String action;

	public String getAction() {
		return action;
	}

	public void setAction(String action) {
		this.action = action;
	}

	public void setTotal(int newTotal) {
		total = newTotal;
	}

	public void setDefaultPageSize(int newDefaultPageSize) {
		defaultPageSize = newDefaultPageSize;
	}

	/**
	 * 调用handler进行分页处理
	 */
	public int doStartTag() throws JspTagException {
		output = new StringBuffer();
		resume = false;
		handler();

		return EVAL_BODY_BUFFERED;
	}

	/**
	 * 获得标记内的记录列表内容
	 */
	public int doAfterBody() throws JspTagException {
		BodyContent bodyContent = getBodyContent();
		if (bodyContent != null) {
			output.append(bodyContent.getString());
			try {
				bodyContent.clear();
			} catch (IOException ex) {
				throw new JspTagException("Fatal IO Error");
			}
		}
		return SKIP_BODY;
	}

	/**
	 * 输出标记内的内容
	 */
	public int doEndTag() throws JspTagException {
		BodyContent bodyContent = getBodyContent();
		try {
			if (bodyContent != null) {
				// 输出结束标记
				output.append("</form>\n");
				// 输出全部内容
				bodyContent.getEnclosingWriter().write(output.toString());
			}
		} catch (IOException ex) {
			throw new JspTagException("Fatal IO Error");
		}

		return EVAL_PAGE;
	}

	/**
	 * 设置标记内变量(每页记录数,当前页号,起始记录号,表单的查询字符串)
	 */
	public void setVariable() {
		pageContext.setAttribute("pageSize", new Integer(pageSize));
		pageContext.setAttribute("pageNo", new Integer(pageNo));
		pageContext.setAttribute("total", new Integer(total));
		pageContext.setAttribute("pages", new Integer(pages));
		pageContext.setAttribute("index", new Integer(index));
	}

	/**
	 * 获取分页信息和其它表单中的变量值并输出表单
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	private void handler() {
		HttpServletRequest request = (HttpServletRequest) pageContext
				.getRequest();

		StringBuffer paramBuf = new StringBuffer();
		HttpSession session = (HttpSession) pageContext.getSession();

		String totalStr = (String) session.getAttribute("total");
		if (totalStr != null) {
			total = Integer.parseInt(totalStr);
			// System.out.println("---------------------------------------"+total);
		}
		try {
			String t = (String) session.getAttribute("defaultPageSize");
			int n = Integer.parseInt(t);
			defaultPageSize = n;
		} catch (Exception e) {
			// 代表没有设置 默认为20
		}

		String choice = "";
		HashMap params = new HashMap();

		// 获得当前页的URI
		@SuppressWarnings("unused")
		String requestURI = request.getRequestURI();

		// 获取操作
		choice = ParamUtil.getParameter(request, "choice");

		// 判断是否转出后返回需恢复原分页及参数信息(判断依据:GET方式访问且没有提供额外参数)
		if (choice.equals("") && request.getMethod().equals("GET")
				&& request.getQueryString() == null) {
			// 是否页面相同
			String pageURI = (String) session.getAttribute("pageURI");
			if (request.getRequestURI().equalsIgnoreCase(pageURI))
				resume = true;
			else
				resume = false;
		}

		if (resume) { // 处理中途转出后返回的情况
			// 从session中取参数
			Object obj = session.getAttribute("pagerParameters");
			if (obj != null) {
				params = (HashMap) obj;

				// 获取每页记录数,若没指定,使用默认值
				pageSize = ((Integer) params.get("pageSize")).intValue();

				// 获取页号
				pageNo = ((Integer) params.get("pageNo")).intValue();
			} else {
				// 提供默认值(一般出在用GET方法查询且不需参数情况的处理,因为条件等同于转出后恢复)
				pageSize = defaultPageSize;
				pageNo = 1;
			}

			// 设定操作
			choice = "current"; // 操作改设为取当前页
		} else {
			// 获取每页记录数,若没指定,使用默认值
			pageSize = ParamUtil.getIntParameter(request, "pageSize",
					defaultPageSize);

			// 获取页号
			pageNo = ParamUtil.getIntParameter(request, "pageNo", 1);
		}

		// 每页记录数越界处理
		if (pageSize <= 0)
			pageSize = 1;

		// 计算总页数
		pages = (total % pageSize == 0) ? total / pageSize : total / pageSize
				+ 1;

		// 根据操作,重新确定当前页号
		if (choice.equals("next"))
			pageNo++;
		if (choice.equals("prev"))
			pageNo--;
		if (choice.equals("first"))
			pageNo = 1;
		if (choice.equals("last"))
			pageNo = pages;

		// 页号越界处理
		if (pageNo > pages)
			pageNo = pages;
		if (pageNo <= 0)
			pageNo = 1;

		// 起始记录号
		index = (pageNo - 1) * pageSize + 1;

		// 输出表单的头
		output.append("<form action='" + action
				+ "' method='post' name='pager'>\n");

		Enumeration enum1;
		String name;
		String value;
		if (resume) { // 处理中途转出后返回的情况
			// 恢复session中的参数
			Collection co = params.entrySet();
			if (co != null) {
				Iterator it = params.entrySet().iterator();
				while (it.hasNext()) {
					Map.Entry e = (Map.Entry) it.next();
					name = (String) e.getKey();
					if (name.equals("pageNo") || name.equals("pageSize")
							|| name.equals("choice")) { // 略过
						continue;
					}
					value = (String) e.getValue();
					paramBuf.append("<input type='hidden' name='" + name
							+ "' value='" + value + "'>\n");
				}
			}
		} else {
			// 获取所有提交的参数,并设置表单"<input type='hidden' name='' value=''>"
			enum1 = request.getParameterNames();

			while (enum1.hasMoreElements()) {
				name = (String) enum1.nextElement();
				value = ParamUtil.getParameter(request, name);
				// 保存查询参数和值
				params.put(name, value);

				if (name.equals("pageNo") || name.equals("pageSize")
						|| name.equals("choice")) {
					continue;
				}
				paramBuf.append("<input type='hidden' name='" + name
						+ "' value='" + value + "'>\n");
			}

			// 保存分页参数和值
			params.put("pageNo", new Integer(pageNo));
			params.put("pageSize", new Integer(pageSize));

			// 保存到session
			session.setAttribute("pagerParameters", params);

			// 保存当前的URI
			session.setAttribute("pageURI", request.getRequestURI());
		} // //////end of if(resume)

		// 输出分页参数表单
		paramBuf.append("<input type='hidden' name='pageNo' value='" + pageNo
				+ "'>\n");
		paramBuf.append("<input type='hidden' name='pageSize' value='"
				+ pageSize + "'>\n");
		paramBuf.append("<input type='hidden' name='choice' value='" + choice
				+ "'>\n");

		output.append(paramBuf.toString());
		setVariable();
		if (resume) {
			// 转出恢复情况下需重新提交表单
			String resend = "<script language='javascript'>"
					+ "document.pager.submit();" + "</script>\n";
			output.append(resend);
		}
	}
}

 

page/ PageSql 

package baoyou.page;


public class PageSql {

	public int getStartIndex(String pageNoStr,String choice,int pageSize,int total) {
		int index = 0;

		if (pageNoStr == "" || pageNoStr == null) {
			pageNoStr = "1";
		} else if (!pageNoStr.matches("^[0-9]{0,30}$")) {
			pageNoStr = "1";
		}

		int pageNo = Integer.parseInt(pageNoStr);
		int pages = (total % pageSize == 0) ? total / pageSize : total
				/ pageSize + 1;

		if (choice != null) {
			if (choice.equals("next"))
				pageNo++;
			if (choice.equals("prev"))
				pageNo--;
			if (choice.equals("first"))
				pageNo = 1;
			if (choice.equals("last"))
				pageNo = pages;
		}
		if (pageNo > pages)
			pageNo = pages;
		if (pageNo <= 0)
			pageNo = 1;

		index = (pageNo - 1) * pageSize;
		return index;
	}
}

 

 page/ PageTEI

package baoyou.page;


import javax.servlet.jsp.tagext.*;

/**
 * 用于page标记的变量预设
 */
public class PageTEI extends TagExtraInfo {
	public VariableInfo[] getVariableInfo(TagData data) {
		return new VariableInfo[] {
				new VariableInfo("pageSize", "java.lang.Integer", true,
						VariableInfo.NESTED),
				new VariableInfo("pageNo", "java.lang.Integer", true,
						VariableInfo.NESTED),
				new VariableInfo("pages", "java.lang.Integer", true,
						VariableInfo.NESTED),
				new VariableInfo("index", "java.lang.Integer", true,
						VariableInfo.NESTED),
				new VariableInfo("total", "java.lang.Integer", true,
						VariableInfo.NESTED) };
	}
}

 

 page/ ParamUtil

package baoyou.page;


import javax.servlet.*;

public class ParamUtil {
	/**
	 * 获得request中指定名称的参数值,若有中文乱码问题请增加转码部分
	 * 
	 * @param request
	 *            ServletRequest对象
	 * @param paramName
	 *            参数名称
	 * @return 如果该变量值存在则返回该值,否则返回""
	 */
	public static String getParameter(ServletRequest request, String paramName) {
		String temp = request.getParameter(paramName);
		if (temp != null && !temp.equals("")) {
			// 若有中文问题,请将下面语句注释
			try {
				temp = new String(temp.getBytes("8859_1"), "UTF-8");
			} catch (Exception e) {
				return "";
			}
			return temp;
		} else {
			return "";
		}
	}

	/**
	 * 获得request中的int型参数值
	 * 
	 * @param request
	 *            ServletRequest对象
	 * @param paramName
	 *            参数名称
	 * @param defaultNum
	 *            默认值,如果没有返回该值
	 * @return 如果该参数值存在则返回其转换为int型的值,否则返回defaultNum
	 */
	public static int getIntParameter(ServletRequest request, String paramName,
			int defaultNum) {
		String temp = request.getParameter(paramName);
		if (temp != null && !temp.equals("")) {
			int num = defaultNum;
			try {
				num = Integer.parseInt(temp);
			} catch (Exception ignored) {
			}
			return num;
		} else {
			return defaultNum;
		}
	}
}// /////////

  

 

 page/ StringUtil

package baoyou.page;


/**
 * <p>
 * Title: 字符串工具类
 * </p>
 * 
 * @version 1.0
 */

public class StringUtil {
	/**
	 * Replaces all instances of oldString with newString in line.
	 * 
	 * @param line
	 *            the String to search to perform replacements on
	 * @param oldString
	 *            the String that should be replaced by newString
	 * @param newString
	 *            the String that will replace all instances of oldString
	 * @return a String will all instances of oldString replaced by newString
	 */
	public static final String replace(String line, String oldString,
			String newString) {
		if (line == null) {
			return null;
		}
		int i = 0;
		if ((i = line.indexOf(oldString, i)) >= 0) {
			char[] line2 = line.toCharArray();
			char[] newString2 = newString.toCharArray();
			int oLength = oldString.length();
			StringBuffer buf = new StringBuffer(line2.length);
			buf.append(line2, 0, i).append(newString2);
			i += oLength;
			int j = i;
			while ((i = line.indexOf(oldString, i)) > 0) {
				buf.append(line2, j, i - j).append(newString2);
				i += oLength;
				j = i;
			}
			buf.append(line2, j, line2.length - j);
			return buf.toString();
		}
		return line;
	}
}

 

 page/ PageBean

package baoyou.bean;

public class PageBean {
	
	private int start;
	
	private int pageSize=20;
	
	private String sql;
	
	private String obj1="";
	
	private String obj2="";
	
	private String obj3="";
	
	private String obj4="";
	
	private String obj5="";
	
	private String obj6="";
	
	private String obj7="";
	
	private String obj8="";
	
	private String obj9="";

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}

	public String getSql() {
		return sql;
	}

	public void setSql(String sql) {
		this.sql = sql;
	}

	public String getObj1() {
		return obj1;
	}

	public void setObj1(String obj1) {
		this.obj1 = obj1;
	}

	public String getObj2() {
		return obj2;
	}

	public void setObj2(String obj2) {
		this.obj2 = obj2;
	}

	public String getObj3() {
		return obj3;
	}

	public void setObj3(String obj3) {
		this.obj3 = obj3;
	}

	public String getObj4() {
		return obj4;
	}

	public void setObj4(String obj4) {
		this.obj4 = obj4;
	}

	public String getObj5() {
		return obj5;
	}

	public void setObj5(String obj5) {
		this.obj5 = obj5;
	}

	public String getObj6() {
		return obj6;
	}

	public void setObj6(String obj6) {
		this.obj6 = obj6;
	}

	public String getObj7() {
		return obj7;
	}

	public void setObj7(String obj7) {
		this.obj7 = obj7;
	}

	public String getObj8() {
		return obj8;
	}

	public void setObj8(String obj8) {
		this.obj8 = obj8;
	}

	public String getObj9() {
		return obj9;
	}

	public void setObj9(String obj9) {
		this.obj9 = obj9;
	}
	
	
	
}

  

  action   UserController 

package baoyou.action;

import java.util.List;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import baoyou.bean.User;
import baoyou.service.UserService;


@Controller
public class UserController {

	@Autowired
	UserService userService;
	
	
	@RequestMapping(value = "/showUserList")
	public String showUserList(HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap, String pageNo,
			String choice, HttpSession session) {
		int total = userService.getCount();
		int pageSize = 10;
		session.setAttribute("total", Integer.toString(total));
		session.setAttribute("defaultPageSize", Integer.toString(pageSize));
		List<User>  list = userService.getList(pageNo, choice, pageSize, total);
		 modelMap.put("list", list);
		return "userlist";
	}
	
}

 

service  UserService   

package baoyou.service;
 
import java.util.List;
import org.springframework.stereotype.Service;
 
import baoyou.bean.PageBean;
import baoyou.bean.User;
import baoyou.bean.UserPool;
import baoyou.page.PageSql;

@Service
public class UserService {

	public List<User> getList(String pageNo,String choice, int pageSize, int total){
		PageBean pageBean = new PageBean();
		int start = new PageSql()
				.getStartIndex(pageNo, choice, pageSize, total);
		pageBean.setPageSize(pageSize);
		pageBean.setStart(start); 
		
		List<User> userList = UserPool.getInstance().getUserList(pageBean);
		return  userList;
	}
	
	public int getCount(){
		return UserPool.getInstance().getCount();
	}
}

 

 

jsp/ userlist.jsp  

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://myself/tags-page" prefix="page"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
</HEAD>
<BODY bgcolor="#F8F8F4"> 
		<table>
			<tbody>
				<tr>
					<td width="20%"><strong>用户ID</strong></td>
					<td width="10%"><strong>用户名</strong></td>
					<td width="10%"><strong>密码</strong></td>

				</tr>
				<c:forEach items="${list}" var="user">
					<tr >
						<td width="20%"><c:out value="${user.userId}" /></td>
						<td width="10%"><c:out value="${user.userName}" /></td>
						<td width="10%"><c:out value="${user.password}" /></td>
					</tr>
				</c:forEach>
			</tbody>
			<tr>
				<td>
					<table>
						<tr>
							<page:pager action="showUserList.htm">
								<td align="right"><page:navigator type="defaultPage"></page:navigator>
								</td>
							</page:pager>
						</tr>
					</table>
				</td>
			</tr>
		</table> 
</BODY>
</HTML>

  

 

tld   page.tld

<?xml version="1.0" encoding="GBK"?>
<!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.0</tlibversion>
  <jspversion>1.1</jspversion>
  <shortname>page</shortname>
  <uri>http://myself/tags-page</uri>
  <info>
    The tag library of Pager
  </info>

  <!--====================page:pager begin=====================-->
  <tag>
    <name>pager</name>
    <tagclass>baoyou.page.PagerTag</tagclass>
    <teiclass>baoyou.page.PageTEI</teiclass>
    <bodycontent>JSP</bodycontent>
    <info>
      pager tag provide the frame of the page divider
    </info>

    <attribute>
      <name>defaultPageSize</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
    <attribute>
      <name>action</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  <!--======================page:pager end=========================-->

  <!--====================page:navigator begin=====================-->
  <tag>
    <name>navigator</name>
    <tagclass>baoyou.page.NavigatorTag</tagclass>

    <bodycontent>JSP</bodycontent>
    <info>
      navigator tag output the Navigator bar which pre-designed
    </info>
    <attribute>
      <name>type</name>
      <required>false</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  <!--======================page:navigator end=========================-->
</taglib>

  

 

 SpringWeb-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
           http://www.springframework.org/schema/context   
           http://www.springframework.org/schema/context/spring-context-3.0.xsd"
	default-autowire="byName">
	<!-- 自动扫描controller bean,把作了注解的类转换为bean -->
	<context:component-scan base-package="baoyou" />
 
	<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
	<!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver"
		p:prefix="jsp/" p:suffix=".jsp">
		<property name="order" value="0" />
	</bean>
	 
</beans>  

  

web.xml 

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee"
	xmlns:jsp="http://java.sun.com/xml/ns/javaee/jsp" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
	id="WebApp_9" version="2.4">
	 
	 
   
   
   <!-- here -->
   <servlet>
		<servlet-name>SpringWeb</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	
	<jsp-config>
	    <taglib>
	      <taglib-uri>http://myself/tags-page</taglib-uri>
	      <taglib-location>/WEB-INF/page.tld</taglib-location>
	    </taglib>
    </jsp-config>
	<servlet-mapping>
		<servlet-name>SpringWeb</servlet-name>
		<url-pattern>*.htm</url-pattern>
	</servlet-mapping>
	
	 
</web-app>

  

 

 

 

 

 

 

你可能感兴趣的:(spring,分页,自定义控件)