Java Web实现分页功能

21 篇文章 1 订阅
5 篇文章 0 订阅

现在一般都采用分页插件来进行分页,方便高效。比如MyBatis提供的pagehelper插件,但面试中,可能面试官会考察分页处理的具体实现,所以,了解一下还是有必要的。

分页的关键点在于知道当前页、每页记录、总记录数等数据,然后构造分页,将分页传回前端,前端进行遍历即可。

1.创建分页PageHelper和实体类Movie

package com.go.page;

import java.util.List;

public class PageHelper<T> {

	private int pageNum;//当前页
	private int pageSize;//每页记录数
	private int totalRecord;//总记录数

	private int totalPage;//总页数,计算得出
	private List<T> list;//存放每页内容
	private int startIndex;//数据库检索位置
	private int start;//开始页码
	private int end;//结束页码
	
	public PageHelper(int pageNum,int pageSize) {
		this.pageNum=pageNum;
		this.pageSize=pageSize;
		this.totalRecord=totalRecord;
		
		this.totalPage=(int) Math.ceil(this.totalRecord*1.0/this.pageSize);
		this.startIndex=(pageNum-1)*pageSize;
		this.start=1;
		this.end=5;
		
		if(totalPage<5)
			this.end=5;
		else{
			this.start=this.pageNum-2;
			this.end=this.pageNum+2;
		}
		if(start<0)
			{
			start=1;
			end=5;
			}
		
		if(end>this.totalPage)
			{
			end=this.totalPage;
			start=end-5;
			}
	}

	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public int getPageSize() {
		return pageSize;
	}

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

	public int getTotalRecord() {
		return totalRecord;
	}

	public void setTotalRecord(int totalRecord) {
		this.totalRecord = totalRecord;
	}

	public int getTotalPage() {
		return totalPage;
	}

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

	public List<T> getList() {
		return list;
	}

	public void setList(List<T> list) {
		this.list = list;
	}

	public int getStartIndex() {
		return startIndex;
	}

	public void setStartIndex(int startIndex) {
		this.startIndex = startIndex;
	}

	public int getStart() {
		return start;
	}

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

	public int getEnd() {
		return end;
	}

	public void setEnd(int end) {
		this.end = end;
	}

}

实体类Movie

public class Movie {

	String movieId;
	String moviename ;
	String director;
	String scenarist;
	String actors;
	String type;
	String country;
	String language;
	String releaseDate;
	String runtime;
	String rate;
	String tags;
	String url;
	String cover;
	public String getDirector() {
		return director;
	}
	public void setDirector(String director) {
		this.director = director;
	}
	public String getScenarist() {
		return scenarist;
	}
	public void setScenarist(String scenarist) {
		this.scenarist = scenarist;
	}
	public String getActors() {
		return actors;
	}
	public void setActors(String actors) {
		this.actors = actors;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
	public String getLanguage() {
		return language;
	}
	public void setLanguage(String language) {
		this.language = language;
	}
	public String getReleaseDate() {
		return releaseDate;
	}
	public void setReleaseDate(String releaseDate) {
		this.releaseDate = releaseDate;
	}
	public String getRuntime() {
		return runtime;
	}
	public void setRuntime(String runtime) {
		this.runtime = runtime;
	}
	public String getTags() {
		return tags;
	}
	public void setTags(String tags) {
		this.tags = tags;
	}
	
	public String getMovieId() {
		return movieId;
	}
	public void setMovieId(String movieId) {
		this.movieId = movieId;
	}
	public String getMovieName() {
		return moviename;
	}
	public void setMovieName(String movieName) {
		this.moviename = movieName;
	}
	public String getRate() {
		return rate;
	}
	public void setRate(String rate) {
		this.rate = rate;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getCoverUrl() {
		return cover;
	}
	public void setCoverUrl(String coverUrl) {
		this.cover = coverUrl;
	}
	public Movie(){}
	public Movie(String movieId, String movieName, String director, String scenarist, String actors, String type,
			String country, String language, String releaseDate, String runtime, String tags, String rate, String url,
			String coverUrl) {
		super();
		this.movieId = movieId;
		this.moviename = movieName;
		this.director = director;
		this.scenarist = scenarist;
		this.actors = actors;
		this.type = type;
		this.country = country;
		this.language = language;
		this.releaseDate = releaseDate;
		this.runtime = runtime;
		this.tags = tags;
		this.rate = rate;
		this.url = url;
		this.cover = coverUrl;
	}
}

2.创建PageController

@Controller
public class PageController {

	@Autowired
	private PageService pageService;

	private static int totalPage;
	@RequestMapping("/findAllMovieWithPage")
	public ModelAndView findAllMovieWithPage(int pageNum, int pageSize) {
		List<Movie> movie = pageService.findAllMovie();
		int totalRecord = movie.size();
		PageHelper<Movie> pb = new PageHelper<Movie>(pageNum, pageSize);
		totalPage = (int) Math.ceil(totalRecord*1.0/pageSize);
		pb.setTotalPage(totalPage);
		int startIndex = pb.getStartIndex();
		pb.setList(pageService.findMovie(startIndex, pageSize));
		ModelAndView mv = new ModelAndView();
		mv.setViewName("movie");
		mv.addObject("moviePage", pb);
		return mv;

	}

	@RequestMapping("/findMovieWithPage")
	public ModelAndView findMovieWithPage(@RequestParam int pageNum, @RequestParam int pageSize) {
		int startIndex = (pageNum - 1) * pageSize;
		PageHelper<Movie> pb = new PageHelper<Movie>(pageNum, pageSize);
		pb.setList(pageService.findMovie(startIndex, pageSize));
		pb.setTotalPage(totalPage);
		ModelAndView mv = new ModelAndView();
		mv.setViewName("movie");
		mv.addObject("moviePage", pb);
		return mv;
	}

}

3.Service

public interface PageService {

	public List<Movie> findAllMovie();

	public List<Movie> findMovie(int startIndex, int pageSize);
}

4.ServiceImpl

@Service
public class PageServiceImpl implements PageService {

	@Autowired
	private JdbcTemplate jdbcTemplate;
	public List<Movie> findAllMovie() {
		String sql = "select moviename,releaseDate,runtime,rate from movie";
		RowMapper<Movie> rowMapper = new BeanPropertyRowMapper<Movie>(
				Movie.class);
		List<Movie> list = jdbcTemplate.query(sql, rowMapper);
		return list;
	}
	public List<Movie> findMovie(int startIndex, int pageSize) {
		String sql = "select moviename,releaseDate,runtime,rate from movie limit "+startIndex+","+pageSize;
		RowMapper<Movie> rowMapper = new BeanPropertyRowMapper<Movie>(
				Movie.class);
		List<Movie> list = jdbcTemplate.query(sql, rowMapper);
		return list;
	}

}

5.spring-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans.xsd 
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context.xsd 
       http://www.springframework.org/schema/tx 
       http://www.springframework.org/schema/tx/spring-tx.xsd
          http://www.springframework.org/schema/mvc
       http://www.springframework.org/schema/mvc/spring-mvc.xsd">

	<!-- 配置扫描的包 -->
	<context:component-scan base-package="com.go.*" />
	<!-- 注册HandlerMapper、HandlerAdapter两个映射类 -->
	<mvc:annotation-driven />
	<!-- 访问静态资源 -->
	<mvc:default-servlet-handler />
	<!-- 视图解析器 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/view/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

	<bean id="jdbcConfig"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location">
			<value>classpath:db.properties</value>
		</property>
	</bean>
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	<property name="user" value="${jdbc.user}"></property>
	<property name="password" value="${jdbc.password}"></property>
	<property name="driverClass" value="${jdbc.driverClass}"></property>
	<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
	</bean>
	
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
	<property name="dataSource" ref="dataSource"></property>
	</bean>
</beans>

6.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
	
	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>
</web-app>

7.db.properties

jdbc.user=root
jdbc.password=123456
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///douban_movie

8.result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<table class="table">
		<thead>

		</thead>
		<tbody>
			<tr>
				<th>电影名称</th>
				<th>上映日期</th>
				<th>时长</th>
				<th>豆瓣评分</th>
			</tr>
			<c:forEach var="movie" items="${moviePage.list}">
				<tr>
					<td>${movie.movieName}</td>
					<td>${movie.releaseDate}</td>
					<td>${movie.runtime}</td>
					<td>${movie.rate}</td>
				</tr>
			</c:forEach>
	</table>
		</tbody>
<a href="/findMovieWithPage.do?pageNum=${moviePage.pageNum-1 }&&pageSize=${moviePage.pageSize}">上一页</a>
<a href="/findMovieWithPage.do?pageNum=${moviePage.pageNum+1 }&&pageSize=${moviePage.pageSize}">下一页</a>
${moviePage.pageNum }/共${moviePage.totalPage}页

</body>
</html>

9.结果(细节方面待完善)

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值