maven+ssm+PageHelper完成分页

文章目录

      • 1 引入pom依赖:
      • 2 建表(mysql):
      • 3 根据数据库创建实体类:
      • 4 UserDao接口:
      • 5 UserDao.xml:也就相当于UserDao的实现类
      • 6 创建Service接口:
      • 7 实现Service接口:
      • 8 Controller
      • 9 jdbc.properties
      • 10 spring-mybatis.xml:
      • 10 springmvc.xml
      • 11 在mybatis-config.xml配置分页插件(必须配置分页)
      • 12 配置 web.xml:
      • 13 文件结构:
      • 14 JSP页面

1 引入pom依赖:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.redocloud</groupId>
    <artifactId>maven-ssm2</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>maven-ssm2 Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <!--统一使用该spring版本-->
        <srping.version>4.0.2.RELEASE</srping.version>

        <!--统一使用该mybatis版本-->
        <mybatis.version>3.2.8</mybatis.version>

        <!--log4j相应版本配置-->
        <slf4j.version>1.7.12</slf4j.version>
        <log4j.version>1.2.17</log4j.version>

        <!--指定项目使用编码-->
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <!--设置jdk版本-->
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <!--支持servlet-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- java ee包 -->
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- spring框架包 start -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${srping.version}</version>
        </dependency>
        <!-- spring框架包 end -->

        <!-- mybatis框架包 start -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- mybatis框架包 end -->

        <!-- 数据库驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.35</version>
        </dependency>

        <!-- 数据库连接池 导入dbcp的jar包,用来在applicationContext.xml中配置数据库 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <!-- jstl标签类 -->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- log start -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log END -->

        <!-- Json  -->
        <!-- 格式化对象,方便输出日志 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.68</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>

        <!-- 上传组件包 start -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.10</version>
        </dependency>
        <!-- 上传组件包 end -->

        <!--引入pageHelper分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.11</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>maven-ssm2</finalName>
        <resources>
            <!--防止出现资源找不到的情况-->
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties
                    **/*.xml</include>
                    <include>**/*.tld
                
                false
            
            
                src/main/java
                
                    **/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>
</project>

2 建表(mysql):

DROP TABLE IF EXISTS `tb_user`;
CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(40) NOT NULL,
  `password` varchar(40) NOT NULL,
  `age` int(4) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_user
-- ----------------------------
INSERT INTO `tb_user` VALUES ('1', '1', '1', '1');
INSERT INTO `tb_user` VALUES ('2', '2', '2', '2');
INSERT INTO `tb_user` VALUES ('3', '张三', '3232322', '22');
INSERT INTO `tb_user` VALUES ('4', '李四', '3232322', '22');
INSERT INTO `tb_user` VALUES ('5', '系统管理', '111', '23');
INSERT INTO `tb_user` VALUES ('6', '系统管理', 'hh', '23');
INSERT INTO `tb_user` VALUES ('7', '5161', '5162', '51');
INSERT INTO `tb_user` VALUES ('8', '333', '22', '11');
INSERT INTO `tb_user` VALUES ('9', 'ctt', '222', '18');
INSERT INTO `tb_user` VALUES ('10', 'zz', '8888', '24');
INSERT INTO `tb_user` VALUES ('11', 'ww', '111', '28');
INSERT INTO `tb_user` VALUES ('12', 'ss', '333', '27');

3 根据数据库创建实体类:

public class User {
    private Integer id;

    private String userName;

    private String password;

    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    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;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }
}

4 UserDao接口:

/**

  • ClassName : UserDao
  • package : com.redocloud.dao
  • 功能描述:
  • @Date : 2020/4/14 0014 17:27
  • @Author : one world
    */
public interface UserDao {
    int deleteByPrimaryKey(Integer id);

    int insert(User record);

    int insertSelective(User record);

    User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(User record);

    int updateByPrimaryKey(User record);

    List<User> findUsers();
}

5 UserDao.xml:也就相当于UserDao的实现类

<?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" >
<!-- namespace的值就是dao接口的完整路径,就这个demo而言namespace 就是userDao.java的完整路径-->
<mapper namespace="com.redocloud.dao.UserDao">
    <resultMap id="BaseResultMap" type="com.redocloud.entity.User">
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="user_name" property="userName" jdbcType="VARCHAR" />
        <result column="password" property="password" jdbcType="VARCHAR" />
        <result column="age" property="age" jdbcType="INTEGER" />
    </resultMap>
    <sql id="Base_Column_List">
        id, user_name, password, age
    </sql>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap"
            parameterType="java.lang.Integer">
        select
        <include refid="Base_Column_List" />
        from tb_user
        where id = #{id,jdbcType=INTEGER}
    </select>
    <select id="findUsers" resultMap="BaseResultMap">
       select * from tb_user
    </select>

    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
        delete from
        tb_user
        where id = #{id,jdbcType=INTEGER}
    </delete>

    <insert id="insert" parameterType="com.redocloud.entity.User">
        insert into tb_user (id,
        user_name, password,
        age)
        values (#{id,jdbcType=INTEGER},
        #{userName,jdbcType=VARCHAR},
        #{password,jdbcType=VARCHAR},
        #{age,jdbcType=INTEGER})
    </insert>
    <insert id="insertSelective" parameterType="com.redocloud.entity.User">
        insert into tb_user
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                id,
            </if>
            <if test="userName != null">
                user_name,
            </if>
            <if test="password != null">
                password,
            </if>
            <if test="age != null">
                age,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=INTEGER},
            </if>
            <if test="userName != null">
                #{userName,jdbcType=VARCHAR},
            </if>
            <if test="password != null">
                #{password,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                #{age,jdbcType=INTEGER},
            </if>
        </trim>
    </insert>

    <update id="updateByPrimaryKeySelective" parameterType="com.redocloud.entity.User">
        update tb_user
        <set>
            <if test="userName != null">
                user_name = #{userName,jdbcType=VARCHAR},
            </if>
            <if test="password != null">
                password = #{password,jdbcType=VARCHAR},
            </if>
            <if test="age != null">
                age = #{age,jdbcType=INTEGER},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>

    <update id="updateByPrimaryKey" parameterType="com.redocloud.entity.User">
        update tb_user
        set
        user_name = #{userName,jdbcType=VARCHAR},
        password =
        #{password,jdbcType=VARCHAR},
        age = #{age,jdbcType=INTEGER}
        where id =
        #{id,jdbcType=INTEGER}
    </update>
</mapper>

6 创建Service接口:

/**
 * ClassName : UserService
 * package : com.redocloud.service
 * 功能描述:
 *
 * @Date : 2020/4/14 0014 17:31
 * @Author : one world
 */
public interface UserService {
    //根据id查找
    public User getUserById(Integer userid);

    //添加一条数据
    public int insert(User user);

    //查找所有
    public List<User> findUsers();
}

7 实现Service接口:

/**
 * ClassName : UserServiceImpl
 * package : com.redocloud.impl
 * 功能描述:
 *
 * @Date : 2020/4/14 0014 17:33
 * @Author : one world
 */
@Transactional
@Service("userService")
public class UserServiceImpl implements UserService {

    /**
     * 因为没有在spring的文件中显式的声明userService实现类,直接通过getBean得到 userService 会找不到
     *  需要显式配置 @Service ("userService"),指定bean的名称
     *  相当与
     */
    @Resource
    private UserDao userDao;

    public User getUserById(Integer userid) {
        return this.userDao.selectByPrimaryKey(userid);
    }

    public int insert(User user) {
        return this.userDao.insert(user);
    }

    public List<User> findUsers() {
        return this.userDao.findUsers();
    }
}

8 Controller

/**
 * ClassName : UserController
 * package : com.redocloud.controller
 * 功能描述:
 *
 * @Date : 2020/4/14 0014 17:36
 * @Author : one world
 */
@Controller
public class UserController {
    /**
     * 使用@Autowired也可以,@Autowired默认按类型装配
     * @Resource 默认按名称装配,当找不到与名称匹配的bean才会按类型装配。
     */
    @Resource
    private UserService userService;
    private static final Logger logger=org.apache.log4j.Logger.getLogger(User.class);

    /**
     * 测试查询
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/showUser")
    public String testtoshowUser(@RequestParam(value = "id") Integer id, Model model) {
        logger.info("通过id查找User");
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "showUser";
    }

    /**Get请求添加用户**/
    @GetMapping("/addUser")
    public String toAddUser(){
        return "addUser";
    }

    /**
     * 测试添加数据
     *
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/insertUser",method = RequestMethod.POST)
    public String testinsertUser(@RequestParam String name,@RequestParam String password,@RequestParam Integer age,Model model) {

        logger.info("用户注册");
        User user = new User();
        user.setUserName(name);
        user.setPassword(password);
        user.setAge(age);
        int count = userService.insert(user);
        System.out.println("插入" + count + "条数据成功");
        model.addAttribute("userName",name);
        model.addAttribute("password",password);
        model.addAttribute("age",age);
        return "showUser";
    }
    /**查看所有用户**/
    @RequestMapping(value = "/findUsers")
    public String findUsers(@RequestParam Integer pageNo,Model model){
        logger.info("查看所有用户");
        //获取指定pageNo页数据,pageSize条数据为一页
        PageHelper.startPage(pageNo,10);
        List<User> list = userService.findUsers();
        //使用PageInfo包装数据
        PageInfo<User> pageInfo = new PageInfo<User>(list);
        model.addAttribute("pageInfo",pageInfo);
        return "list";
    }

}

9 jdbc.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/maven-ssm2?useUnicode=true&characterEncoding=UTF-8
username=root
password=322728

initialSize=0 
maxActive=20 
maxIdle=20
minIdle=1
maxWait=60000

10 spring-mybatis.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:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
">

    <!-- 自动扫描 -->
    <context:component-scan base-package="com.redocloud.entity" >
    <!-- 不扫描@Controller注解的类-->
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 引入配置文件 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="${driver}" />
        <property name="url" value="${url}" />
        <property name="username" value="${username}" />
        <property name="password" value="${password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}"></property>
    </bean>

    <!-- spring和MyBatis整合,不需要mybatis的配置映射文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- 自动扫描mapping.xml文件 -->
        <property name="mapperLocations" value="classpath:com/redocloud/mapping/*.xml"></property>
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
    </bean>

    <!-- DAO接口所在包名,Spring会自动查找其下的类 动态代理实现 不用写dao的实现类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.redocloud.dao" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>
    <!--service-->
    <bean id= "userService" class = "com.redocloud.impl.UserServiceImpl"/>

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

10 springmvc.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: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-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!-- 自动扫描该包 @controller注解的类-->
    <context:component-scan base-package="com.redocloud.controller"/>

    <!-- 静态资源处理 将springmvc不能处理的请求交给tomcat -->
    <mvc:default-servlet-handler/>

    <!--自动注册 RequestMappingHandlerMapping、RequestMappingHandlerAdapter 等bean -->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- 定义跳转的文件的前后缀 ,视图模式配置-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/pages/views/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

11 在mybatis-config.xml配置分页插件(必须配置分页)

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 配置分页插件 -->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库-->
            <property name="helperDialect" value="mysql"/>
        </plugin>
    </plugins>
</configuration>

12 配置 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/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>maven-web-demo02</display-name>
  <!-- 编码过滤器 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <async-supported>true</async-supported>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <!-- Spring监听器 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-mybatis.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--Spring MVC 配置servlet -->
  <servlet>
    <servlet-name>springDispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springDispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

13 文件结构:

maven+ssm+PageHelper完成分页_第1张图片

14 JSP页面

addUser.jsp:

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020/4/15 0015
  Time: 0:04
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <!--使用..-->
    <script type="text/javascript" src="../js/jquery-3.4.1.min.js"></script>
    <script type="text/javascript">
        function register() {
            var name = $("#name").val();
            var password = $("#password").val();
            var age = $("#age").val();
            $.ajax({
                //此处这个写法是访问本文件路径下的insertUser(也就是访问了错误路径)
                // ,但是我们实际是要访问项目中controller的insertUser
                url:'../../insertUser',
                type:'POST',
                data:{name:name,password:password,age:age},
                timeout:5000,
                dataType:'text',
                success:function (data) {
                  if(data!=null){
                      location.href="list.jsp"
                  }
                }
            })
        }
    </script>
</head>
<body>
 姓名:<input type="text" name="name" id="name"/><br>
密码 :<input type="password" name="password" id="password"/><br>
 年龄:<input type="text" name="age" id="age"/><br>
 <input type="button" value="提交" onclick="register()"/>
</body>
</html>

list.jsp:

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020/4/15 0015
  Time: 4:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>用户</title>
    <%
     pageContext.setAttribute("basePath",request.getContextPath());
    %>
    <script type="text/javascript" src="${basePath}/pages/js/jquery-3.4.1.min.js"></script>
    <link href="${basePath}/pages/js/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="${basePath}/pages/js/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<table class="table table-bordered">
    <thead>
     <tr>
         <th>id</th>
         <th>username</th>
         <th>password</th>
         <th>age</th>
     </tr>
    </thead>
    <c:forEach items="${pageInfo.list}" var="users">
    <tr>
        <td>${users.id}</td>
        <td>${users.userName}</td>
        <td>${users.password}</td>
        <td>${users.age}</td>
    </tr>
</c:forEach>
    <tfoot>

    <tr >
        <td colspan="6" align="center">
            <ul class="pagination">
                <li><a href="findUsers?pageNo=1"> 首页</a>
                    <!-- 上一页 -->
                    <c:if test="${pageInfo.hasPreviousPage }">
                <li><a href="findUsers?pageNo=${pageInfo.pageNum-1 }" aria-label="Previous"> <span aria-hidden="true">&laquo;</span></a></li>
                </c:if>
                <!-- 当前页 -->
                <c:forEach	items="${ pageInfo.navigatepageNums}" var="page_Num">
                    <c:if test="${page_Num==pageInfo.pageNum }">
                        <li class="active"><a href="#">${page_Num}</a></li>
                    </c:if>

                    <c:if test="${page_Num!=pageInfo.pageNum }">
                        <li><a href="findUsers?pageNo=${page_Num}">${page_Num}</a></li>
                    </c:if>
                </c:forEach>
                <!-- 下一页 -->
                <c:if test="${pageInfo.hasNextPage }">
                    <li><a href="findUsers?pageNo=${pageInfo.pageNum+1 }"	aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li>
                </c:if>
                <li><a href="findUsers?pageNo=${pageInfo.pages}"> 尾页</a></li>
            </ul>
        </td>
    </tr>

    </tfoot>
</table>
</body>
</html>

showUser.jsp:

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2020/4/14 0014
  Time: 21:19
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!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>
id:${user.id} <br>
userName: ${user.userName} <br>
password: ${user.password} <br>
age: ${user.age} <br>
</body>
</html>

index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!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>
<a href="showUser?id=2">ShowUser page</a><br>
<a href="findUsers?pageNo=1">list</a><br>
<a href="/maven_ssm2_war/pages/views/addUser.jsp">insertUser </a>
</body>
</html>

点击clean后,等控制台显示清除完后,再点击package,控制台显示成功后运行结果:
maven+ssm+PageHelper完成分页_第2张图片
showUser Page: id写死了,为2
maven+ssm+PageHelper完成分页_第3张图片
list分页:
maven+ssm+PageHelper完成分页_第4张图片
maven+ssm+PageHelper完成分页_第5张图片

链接:https://pan.baidu.com/s/17eH-I9p-81zZad_eLa8_aA
提取码:asjb

有问题时,可以参考:https://blog.csdn.net/qq_42739776/article/details/105475730

博主是小白,代码中可能仍存在很多问题,如果有幸能被大神看到!希望大佬指点一二,感激不尽!

你可能感兴趣的:(#,Spring项目)