栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

通用分页02(前端)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

通用分页02(前端)

今天所要讲的是关于前端的通用分页

目录

一、改造pagebean

二、分页查询


一、改造pagebean

所需条件:

        ①需要新增变量保存上一次查询条件;

        ②需要新增变量保存上一次请求地址;比如:http://localhost:8080/t280_page/book/search

        ③需要添加方法:获取最大页的页码;

        ④需要添加方法:获取下一页的页码;

        ⑤需要添加方法:获取上一页的页码;

        ⑥需要增加方法:初始化pagebean。

PageBean类:
package com.ycx.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;


public class PageBean {

	private int page = 1;// 页码

	private int rows = 10;// 页大小

	private int total = 0;// 总记录数

	private boolean pagination = true;// 是否分页
	
//	 需要新增变量保存上一次请求地址;比如:http://localhost:8080/t280_page/book/search
	private String url;
	
//	 需要新增变量保存上一次查询条件
	private Map parameterMap = new HashMap<>();

//	 需要添加方法:获取最大页的页码
	public int maxPage() {
		return this.total % this.rows == 0 ?
				this.total / this.rows
				: this.total / this.rows+1;
	}

//	 需要添加方法:获取上一页的页码;
	public int previousPage() {
		return this.page > 1 ? this.page-1 : this.page;
	}

	
//	 需要添加方法:获取下一页的页码	
	public int nextPage() {
		return this.page < this.maxPage()?
				this.page+1:this.page;
	}

//	 需要增加方法:初始化pagebean
	public void setRequest(HttpServletRequest req) {
		this.setPage(req.getParameter("page"));
		this.setRows(req.getParameter("rows"));
		this.setPagination(req.getParameter("pagination"));
		this.setUrl(req.getRequestURI().toString());
		this.setParameterMap(req.getParameterMap());
	}
	
	private void setPagination(String pagination) {
		if(StringUtils.isNotBlank(pagination)) {
			this.setPagination(!"false".equals(pagination));
		}
	
}

	private void setRows(String rows) {
		if(StringUtils.isNotBlank(rows)) {
			this.setRows(Integer.valueOf(rows));
		}
}

	public void setPage(String page) {
		if(StringUtils.isNotBlank(page)) {
	//		set自动生成的方法
			this.setPage(Integer.valueOf(page));
		}
	}

	
	
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map getParameterMap() {
		return parameterMap;
	}

	public void setParameterMap(Map parameterMap) {
		this.parameterMap = parameterMap;
	}

	public PageBean() {
		super();
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() {
		return pagination;
	}

	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}

	
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
				+ ", url=" + url + ", parameterMap=" + parameterMap + "]";
	}

	
}
然后新建一个 BookServlet :
package com.ycx.web;

import java.io.IOException;
import java.util.Map;

import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ycx.util.PageBean;

@WebServlet("/book/search")
public class BookServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		PageBean pageBean=new PageBean();
		pageBean.setRequest(req);
	
		req.setAttribute("pagebean", pageBean);
		req.getRequestDispatcher("/bookList.jsp").forward(req, resp);
	
	
	}
}
bookList.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




Insert title here


${pagebean }

 运行结果:

 然后使用debug查看:

二、分页查询

接着我们以一个书籍列表为案例:

bookList.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>






书籍列表



	
书籍ID 书籍名 价格
1 圣墟第1章 1
1 圣墟第1章 1

 目前我们的页面效果是这样的,数据暂时都是定死的,并且无法查看上一页、下一页、尾页:

前端首先要显示界面,自己建一个tag标签包(PageTag),然后通过上节课学得知识自定义标签来写一个page标签,最后在index界面中直接写出自己定义的标签就行。 接下来要给它新建一个PageTag类:
package com.ycx.tag;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;


import com.ycx.util.PageBean;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class PageTag extends BodyTagSupport{
	private PageBean pageBean;
	
	public PageBean getPageBean() {
		return pageBean;
	}

	public void setPageBean(PageBean pageBean) {
		this.pageBean = pageBean;
	}

	
	
	
	@Override
	public int doStartTag() throws JspException {
		JspWriter out = pageContext.getOut();
		try {
			out.print(toHTML());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return super.doStartTag();
	}

	private String toHTML() {
		StringBuffer sb=new StringBuffer();
//		隐藏的form表单,作用保存上一次查询条件
		sb.append("
"); sb.append(" "); Map parameterMap = pageBean.getParameterMap(); if(parameterMap != null && parameterMap.size() > 0) { Set> entrySet = parameterMap.entrySet(); for (Entry entry : entrySet) { String key = entry.getKey();// name/likes/page/rows String[] values = entry.getValue(); if(!"page".equals(key)) { for (String value : values) { sb.append(" "); } } } } sb.append(""); // 分页条 sb.append("
    "); sb.append("
  • 首页
  • "); sb.append("
  • <
  • "); sb.append("
  • "+pageBean.getPage()+"
  • "); sb.append("
  • >
  • "); sb.append("
  • 尾页
  • "); sb.append("
  • 到第
  • "); sb.append("
  • 确定
  • "); sb.append("
  • 共"+pageBean.getTotal()+"条
  • "); sb.append("
"); // 分页js代码 sb.append(""); return sb.toString(); } }

继承 BodyTagSupport类,用stringbuffer中的append方法来实现页面展示效果。

最后在index中写好    即可。 看ycx.tld代码:



    
  JSTL 1.1 core library
  JSTL core
  1.1
  y
  http://ycx.com

  
    
        Provides core validation features for JSTL tags.
    
    
        org.apache.taglibs.standard.tlv.JstlCoreTLV
    
  
  
	
  page
  
    com.ycx.tag.PageTag
    
    JSP
    
   
        pageBean
       
        true
       
        true
     
  


 分页得核心思想:当点击下一页时,有许多参数是不变的,比如像名字,行数,以及总页数,但是其中有一个参数要变,那就是page(页数) 优化PageBean代码:
package com.ycx.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;


public class PageBean {

	private int page = 1;// 页码

	private int rows = 10;// 页大小

	private int total = 0;// 总记录数

	private boolean pagination = true;// 是否分页
	
//	 需要新增变量保存上一次请求地址;比如:http://localhost:8080/t280_page/book/search
	private String url;
	
//	 需要新增变量保存上一次查询条件
	private Map parameterMap = new HashMap<>();

//	 需要添加方法:获取最大页的页码
	public int maxPage() {
		return this.total % this.rows == 0 ?
				this.total / this.rows
				: this.total / this.rows+1;
	}

//	 需要添加方法:获取上一页的页码;
	public int previousPage() {
		return this.page > 1 ? this.page-1 : this.page;
	}

	
//	 需要添加方法:获取下一页的页码	
	public int nextPage() {
		return this.page < this.maxPage()?
				this.page+1:this.page;
	}

//	 需要增加方法:初始化pagebean
	public void setRequest(HttpServletRequest req) {
		this.setPage(req.getParameter("page"));
		this.setRows(req.getParameter("rows"));
		this.setPagination(req.getParameter("pagination"));
		this.setUrl(req.getRequestURI().toString());
		this.setParameterMap(req.getParameterMap());
	}
	
	private void setPagination(String pagination) {
		if(StringUtils.isNotBlank(pagination)) {
			this.setPagination(!"false".equals(pagination));
		}
	
}

	private void setRows(String rows) {
		if(StringUtils.isNotBlank(rows)) {
			this.setRows(Integer.valueOf(rows));
		}
}

	public void setPage(String page) {
		if(StringUtils.isNotBlank(page)) {
	//		set自动生成的方法
			this.setPage(Integer.valueOf(page));
		}
	}

	
	
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map getParameterMap() {
		return parameterMap;
	}

	public void setParameterMap(Map parameterMap) {
		this.parameterMap = parameterMap;
	}

	public PageBean() {
		super();
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() {
		return pagination;
	}

	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}

	
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
				+ ", url=" + url + ", parameterMap=" + parameterMap + "]";
	}

	
}
紧接着在bookList.jsp内导入我的y标签和c标签:
	<%@taglib uri="http://ycx.com" prefix="y" %>
	<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 接着写一个BookServlet:
package com.ycx.web;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ycx.dao.BookDao;
import com.ycx.entity.Book;
import com.ycx.util.PageBean;

@WebServlet("/book/search")
public class BookServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		req.getParameter("name");
//		req.getParameterValues("likes");
		
//		Map parameterMap = req.getParameterMap();//name
//	
		PageBean pageBean=new PageBean();
		pageBean.setRequest(req);
		BookDao bookDao=new BookDao();
		Book book=new Book();
		book.setBname(req.getParameter("bname"));
		try {
			List books = bookDao.list2(book, pageBean);
			req.setAttribute("books", books);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		req.setAttribute("pagebean", pageBean);
		req.getRequestDispatcher("/bookList.jsp").forward(req, resp);
	
	
	}
}
再利用c:forEach标签把数据遍历出来,展示在页面上去, bookList.jsp代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
	<%@taglib uri="http://ycx.com" prefix="y" %>
	<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>






书籍列表



	
书籍ID 书籍名 价格
${b.bid } ${b.bname } ${b.price }
运行效果如下:

 但是我们还面临一个问题,就是搜索时乱码, 比如搜索“圣墟”,如下图所示:

 搜索出来是乱码的情况。

那么我们就要去解决,我们需在EncodingFiter类里面去处理:
package com.ycx.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebFilter("/book/*")
public class EncodingFiter implements Filter {

	private String encoding = "UTF-8";// 默认字符集

	public EncodingFiter() {
		super();
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		// 中文处理必须放到 chain.doFilter(request, response)方法前面
		res.setContentType("text/html;charset=" + this.encoding);
		if (req.getMethod().equalsIgnoreCase("post")) {
			req.setCharacterEncoding(this.encoding);
		} else {
			Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
			Set set = map.keySet();// 取出所有参数名
			Iterator it = set.iterator();
			while (it.hasNext()) {
				String name = (String) it.next();
				String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
				for (int i = 0; i < values.length; i++) {
					values[i] = new String(values[i].getBytes("ISO-8859-1"),
							this.encoding);
				}
			}
		}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
		if (null != s && !s.trim().equals("")) {
			this.encoding = s.trim();
		}
	}

}
我们再去用DeBug测试,搜索“圣墟”:

 就解决了~

                                                                首页:

尾页:   总结:通用分页把它简单化就分成前端和后台,其中公用的写到一个类里面就能减少代码量和大量时间,要抓住核心思想,这样才能事半功倍!我们下期再见叭~

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/993499.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号