2018.5.2
仅为个人理解 不足之处欢迎指正~
“分页”是一个很常见的场景 各类网站在需要显示的数据较多时 几乎都会采用分页操作带给用户良好的体验
而分页的方式也有许多种 有通过前端实现的也有通过后端实现的
后端上的实现方式有通过Mysql的Limit功能或者使用插件等不同方式
本文在前文的项目(登录注册)基础上 模拟一个浏览所有用户的功能
实现一个简单的分页例子
最终项目结构:
结果展示:
额外添加的包:
jstl 1.2
第一步:Page.java的编写
package pojo;
import java.util.List;
public class Page<T>
{
private int nowPage; //当前页数
private int pageSize;//每一页的规模
private int totalCount;//总记录条数
private int totalPage;//总页数
private List<T> lists;//每页的显示的数据
public int getNowPage() {
return nowPage;
}
public void setNowPage(int nowPage) {
this.nowPage = nowPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public List<T> getLists() {
return lists;
}
public void setLists(List<T> lists) {
this.lists = lists;
}
}
采用这种形式的配置可以提高灵活性,目前仅需要对“User”信息进行分页,而以后或许需要对各类信息进行分页 所以一个List<T>可以被任何pojo类应用
第二步:dao层内容的编写
UserDao.java
package dao;
import java.util.HashMap;
import java.util.List;
import org.mybatis.spring.annotation.MapperScan;
import pojo.User;
@MapperScan
public interface UserDao
{
User getUserByusername(String username); //根据用户名获取用户
void addUser(User user); //注册用户
int selectCount(); //查询用户总数
List<User> findByPage(HashMap<String,Object> map);//分页操作(limit)
}
本文添加了两个新的方法并加以实现
UserDao.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.UserDao">
<resultMap id="BaseResultMap" type="pojo.User">
<result column="userName" property="username" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="phone" property="phone" jdbcType="VARCHAR" />
<result column="email" property="email" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List">
username,password,phone,email
</sql>
<!-- 添加用户 -->
<insert id="addUser" parameterType="pojo.User" >
insert into user values (#{username},#{password},#{phone},#{email})
</insert>
<!-- 根据用户名查找用户 -->
<select id="getUserByusername" parameterType="string" resultType="pojo.User">
select * from user where username=#{username}
</select>
<!-- 查询用户总数 -->
<select id="selectCount" resultType="int">
select count(*) from user
</select>
<!-- 根据分页数据start和size查询数据 -->
<select id="findByPage" parameterType="Map" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from user
<if test="start!=null and size!=null">
limit #{start},#{size}
</if>
</select>
</mapper>
有几个地方需要注意:
resultType为Map的配置
下文中复用语句的配置
两个新功能的实现 <include>标签是对sql语句的复用
第三步:service层内容的编写
UserService.java
package service;
import pojo.Page;
import pojo.User;
public interface UserService
{
void addUser(User user);//注册用户
String login(User user);//登录
int selectCount();//查询用户总数
Page<User> findByPage(int nowPage);//分页查询用户
}
本文添加了两个新方法并加以实现:
UserServiceImpl.java
package service;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import pojo.Login;
import pojo.Page;
import pojo.User;
import dao.UserDao;
@Service
public class UserServiceImpl implements UserService
{
@Resource
UserDao userdao;
@Override
public void addUser(User user)
{
System.out.println("注册信息为:");
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println(user.getPhone());
System.out.println(user.getEmail());
userdao.addUser(user);
}
@Override
public String login(User user)
{
System.out.println("尝试登录");
String username=user.getUsername();
User trueuser=userdao.getUserByusername(username);
if(trueuser.getPassword().equals(user.getPassword()))
{
return "登录成功";
}
else
{
return "密码错误";
}
}
@Override
public int selectCount() //查询用户总数
{
return userdao.selectCount();
}
@Override
public Page<User> findByPage(int nowPage)
{
HashMap<String,Object> map=new HashMap<String,Object>();
Page<User> page=new Page<User>();
//封装当前页数
page.setNowPage(nowPage);
//设置每页显示的数据
int pageSize=3;
page.setPageSize(pageSize);
//设置总记录数量
int totalCount=userdao.selectCount();
page.setTotalCount(totalCount);
//设置总页数
double tc=totalCount;
Double num=Math.ceil(tc/pageSize); //若最后一面显示不满,需向上取整
page.setTotalPage(num.intValue());
map.put("start", (nowPage-1)*pageSize);
map.put("size", page.getPageSize());
List<User> lists=userdao.findByPage(map);
page.setLists(lists);
return page;
}
}
在这里设置每页显示的数据数量:
第四步:新controller的编写
UserController.java
package controller;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import pojo.Page;
import pojo.User;
import service.UserService;
@Controller
public class UserController
{
@Resource
UserService userService;
@RequestMapping("/ListUser")
public String ListUser
(@RequestParam(value="nowPage",defaultValue="1",required=false)
int nowPage,Model model)
{
model.addAttribute("pagemsg",userService.findByPage(nowPage));
return "ListUser";
}
}
第五步:ListUser.jsp的编写
在view下编写新的页面ListUser.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>用户列表</title>
</head>
<body>
用户列表:
<br>
<table align="center" border='1' cellpadding="10" class="table1">
<tr>
<td>username</td>
<td>phone</td>
<td>email</td>
</tr>
<br>
<c:forEach items="${requestScope.pagemsg.lists}" var="u">
<tr>
<th>${u.username}</th>
<th>${u.phone}</th>
<th>${u.email}</th>
</tr>
</c:forEach>
<table border="0" cellspacing="0" cellpadding="0" width="900px">
<tr>
<td class="td2">
<span>第${requestScope.pagemsg.nowPage }/ ${requestScope.pagemsg.totalPage}页</span>
<span>总记录数:${requestScope.pagemsg.totalCount } 每页显示:${requestScope.pagemsg.pageSize}</span>
<span>
<c:if test="${requestScope.pagemsg.nowPage != 1}">
<a href="${pageContext.request.contextPath }/ListUser?nowPage=1">[首页]</a>
<a href="${pageContext.request.contextPath }/ListUser?nowPage=${requestScope.pagemsg.nowPage-1}">[上一页]</a>
</c:if>
<c:if test="${requestScope.pagemsg.nowPage != requestScope.pagemsg.totalPage}">
<a href="${pageContext.request.contextPath }/ListUser?nowPage=${requestScope.pagemsg.nowPage+1}">[下一页]</a>
<a href="${pageContext.request.contextPath }/ListUser?nowPage=${requestScope.pagemsg.totalPage}">[尾页]</a>
</c:if>
</span>
</td>
</tr>
</table>
</body>
</html>
特别需要注意的是:
其他:
(1)Maven配置文件pom.xml
<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tzy</groupId>
<artifactId>MVCDemo2</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>MVCDemo1 Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.3.0.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.0.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.0.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.0.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.34</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.3.2.RELEASE</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<scope>compile</scope>
</dependency>
</dependencies>
<repositories>
<repository>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Central Repository</name>
<url>http://repo.maven.apache.org/maven2</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<releases>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
</snapshots>
<id>central</id>
<name>Central Repository</name>
<url>http://repo.maven.apache.org/maven2</url>
</pluginRepository>
</pluginRepositories>
<build>
<sourceDirectory>D:\WorkspaceforME\MVCDemo2 Maven Webapp\src\main\java</sourceDirectory>
<scriptSourceDirectory>D:\WorkspaceforME\MVCDemo2 Maven Webapp\src\main\scripts</scriptSourceDirectory>
<testSourceDirectory>D:\WorkspaceforME\MVCDemo2 Maven Webapp\src\test\java</testSourceDirectory>
<outputDirectory>D:\WorkspaceforME\MVCDemo2 Maven Webapp\target\classes</outputDirectory>
<testOutputDirectory>D:\WorkspaceforME\MVCDemo2 Maven Webapp\target\test-classes</testOutputDirectory>
<resources>
<resource>
<directory>D:\WorkspaceforME\MVCDemo2 Maven Webapp\src\main\resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>D:\WorkspaceforME\MVCDemo2 Maven Webapp\src\test\resources</directory>
</testResource>
</testResources>
<directory>D:\WorkspaceforME\MVCDemo2 Maven Webapp\target</directory>
<finalName>TestMaven2</finalName>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.3</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.2-beta-5</version>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
</plugin>
<plugin>
<artifactId>maven-release-plugin</artifactId>
<version>2.0</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<executions>
<execution>
<id>default-testCompile</id>
<phase>test-compile</phase>
<goals>
<goal>testCompile</goal>
</goals>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</execution>
<execution>
<id>default-compile</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</execution>
</executions>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.4.1</version>
<executions>
<execution>
<id>default-clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.3.1</version>
<executions>
<execution>
<id>default-install</id>
<phase>install</phase>
<goals>
<goal>install</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>2.5</version>
<executions>
<execution>
<id>default-resources</id>
<phase>process-resources</phase>
<goals>
<goal>resources</goal>
</goals>
</execution>
<execution>
<id>default-testResources</id>
<phase>process-test-resources</phase>
<goals>
<goal>testResources</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.10</version>
<executions>
<execution>
<id>default-test</id>
<phase>test</phase>
<goals>
<goal>test</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<executions>
<execution>
<id>default-war</id>
<phase>package</phase>
<goals>
<goal>war</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.7</version>
<executions>
<execution>
<id>default-deploy</id>
<phase>deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.0</version>
<executions>
<execution>
<id>default-site</id>
<phase>site</phase>
<goals>
<goal>site</goal>
</goals>
<configuration>
<outputDirectory>D:\WorkspaceforME\MVCDemo2 Maven Webapp\target\site</outputDirectory>
<reportPlugins>
<reportPlugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
</reportPlugin>
</reportPlugins>
</configuration>
</execution>
<execution>
<id>default-deploy</id>
<phase>site-deploy</phase>
<goals>
<goal>deploy</goal>
</goals>
<configuration>
<outputDirectory>D:\WorkspaceforME\MVCDemo2 Maven Webapp\target\site</outputDirectory>
<reportPlugins>
<reportPlugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
</reportPlugin>
</reportPlugins>
</configuration>
</execution>
</executions>
<configuration>
<outputDirectory>D:\WorkspaceforME\MVCDemo2 Maven Webapp\target\site</outputDirectory>
<reportPlugins>
<reportPlugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-project-info-reports-plugin</artifactId>
</reportPlugin>
</reportPlugins>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<outputDirectory>D:\WorkspaceforME\MVCDemo2 Maven Webapp\target\site</outputDirectory>
</reporting>
</project>
(2)spring配置文件SpringConfig.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/tool"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.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/tool
http://www.springframework.org/schema/tool/spring-tool.xsd">
<!--配置数据源-->
<bean id="jdbcDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mvcdemo2?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!--配置sessionFactory-->
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="jdbcDataSource" />
<property name="mapperLocations">
<array>
<value>classpath:Dao/**/*.xml</value>
</array>
</property>
<property name="typeAliasesPackage" value="com.isea533.mybatis.model"/>
<!-- MybatisSpringPageInterceptor分页拦截器 -->
<!--<property name="plugins">-->
<!--<bean class="com.wlxk.Util.MybatisSpringPageInterceptor"/>-->
<!--</property>-->
</bean>
<!--配置dao 自动扫描带有@MapperScan注解的-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="dao"/>
<property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
</bean>
<bean id="Timeprint" class="aspect.Timeprint">
</bean>
<aop:config>
<aop:aspect id="time1" ref="Timeprint">
<aop:pointcut id="test1"
expression="execution(* service.UserService.*(..))"/>
<aop:before method="printTime" pointcut-ref="test1"/>
<aop:after method="printTime" pointcut-ref="test1"/>
</aop:aspect>
</aop:config>
<!--全局异常处理-->
<!--service 注解扫描-->
<context:component-scan base-package="service"/>
</beans>
总结:
利用limit进行分页较为麻烦
其中的逻辑虽不难理解但是仍较为繁琐 容易出现疏忽
调试之中遇到了一些问题 最大的问题还是对前端页面的编写 在这方面缺失了太多知识
jsp页面编写用了大量的EL表达式 这其中很多函数用法还不够熟悉
以前的测试基本都是用PostMan完成的 这也是导致偏科的巨大因素
从这个项目开始给自己定下目标所有的view层都要写出来 不考虑页面美观仅仅是最基本的数据交互
写页面还是有丶烦躁
下一步会尝试用github上的插件PageHelper完成分页
谢谢~