• SpringMVC-SSM整合/分页插件PageHelper案例


    目录

    一、Spring+Mybatis+SpringMVC

    1.1 依赖配置

    1.2 Web.xml

    1.3 SpringMVC.xml

    1.4 Spring.xml

    1.5 mybatis-config.xml

    1.6 log4j.xml

    1.7 jdbc.properties

    二、分页插件PageHelper

    2.1 配置

    2.2 使用

    2.3 Demo


    一、Spring+Mybatis+SpringMVC

            项目结构:

    1.1 依赖配置

    1. <project xmlns="http://maven.apache.org/POM/4.0.0"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. <modelVersion>4.0.0modelVersion>
    5. <groupId>org.examplegroupId>
    6. <artifactId>SSM_2022artifactId>
    7. <version>1.0-SNAPSHOTversion>
    8. ------------------------------------------------------------------------------------
    9. <properties>
    10. <maven.compiler.source>8maven.compiler.source>
    11. <maven.compiler.target>8maven.compiler.target>
    12. <spring.version>5.3.1spring.version>
    13. properties>
    14. <packaging>warpackaging>
    15. <dependencies>
    16. <dependency>
    17. <groupId>org.springframeworkgroupId>
    18. <artifactId>spring-contextartifactId>
    19. <version>${spring.version}version>
    20. dependency>
    21. <dependency>
    22. <groupId>org.springframeworkgroupId>
    23. <artifactId>spring-beansartifactId>
    24. <version>${spring.version}version>
    25. dependency>
    26. <dependency>
    27. <groupId>org.springframeworkgroupId>
    28. <artifactId>spring-webartifactId>
    29. <version>${spring.version}version>
    30. dependency>
    31. <dependency>
    32. <groupId>org.springframeworkgroupId>
    33. <artifactId>spring-webmvcartifactId>
    34. <version>${spring.version}version>
    35. dependency>
    36. <dependency>
    37. <groupId>org.springframeworkgroupId>
    38. <artifactId>spring-jdbcartifactId>
    39. <version>${spring.version}version>
    40. dependency>
    41. <dependency>
    42. <groupId>org.springframeworkgroupId>
    43. <artifactId>spring-aspectsartifactId>
    44. <version>${spring.version}version>
    45. dependency>
    46. <dependency>
    47. <groupId>org.springframeworkgroupId>
    48. <artifactId>spring-testartifactId>
    49. <version>${spring.version}version>
    50. dependency>
    51. <dependency>
    52. <groupId>org.mybatisgroupId>
    53. <artifactId>mybatisartifactId>
    54. <version>3.5.7version>
    55. dependency>
    56. <dependency>
    57. <groupId>org.mybatisgroupId>
    58. <artifactId>mybatis-springartifactId>
    59. <version>2.0.6version>
    60. dependency>
    61. <dependency>
    62. <groupId>com.alibabagroupId>
    63. <artifactId>druidartifactId>
    64. <version>1.0.9version>
    65. dependency>
    66. <dependency>
    67. <groupId>junitgroupId>
    68. <artifactId>junitartifactId>
    69. <version>4.12version>
    70. <scope>testscope>
    71. dependency>
    72. <dependency>
    73. <groupId>mysqlgroupId>
    74. <artifactId>mysql-connector-javaartifactId>
    75. <version>8.0.16version>
    76. dependency>
    77. <dependency>
    78. <groupId>log4jgroupId>
    79. <artifactId>log4jartifactId>
    80. <version>1.2.17version>
    81. dependency>
    82. <dependency>
    83. <groupId>com.github.pagehelpergroupId>
    84. <artifactId>pagehelperartifactId>
    85. <version>5.2.0version>
    86. dependency>
    87. <dependency>
    88. <groupId>ch.qos.logbackgroupId>
    89. <artifactId>logback-classicartifactId>
    90. <version>1.2.3version>
    91. dependency>
    92. <dependency>
    93. <groupId>javax.servletgroupId>
    94. <artifactId>javax.servlet-apiartifactId>
    95. <version>3.1.0version>
    96. <scope>providedscope>
    97. dependency>
    98. <dependency>
    99. <groupId>com.fasterxml.jackson.coregroupId>
    100. <artifactId>jackson-databindartifactId>
    101. <version>2.12.1version>
    102. dependency>
    103. <dependency>
    104. <groupId>commons-fileuploadgroupId>
    105. <artifactId>commons-fileuploadartifactId>
    106. <version>1.3.1version>
    107. dependency>
    108. <dependency>
    109. <groupId>org.thymeleafgroupId>
    110. <artifactId>thymeleaf-spring5artifactId>
    111. <version>3.0.12.RELEASEversion>
    112. dependency>
    113. dependencies>
    114. project>

    1.2 Web.xml

            Spring提供了监听ContextLoaderListener,实现ServletContextListener接口,可监听 ServletContext的状态,在web服务器启动时读取Spring的配置文件,创建Spring的IOC容器。Spring的IOC容器的创建必须早于SpringMVC的IOC容器的创建

    1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    4. version="4.0">
    5. <filter>
    6. <filter-name>CharacterEncodingFilterfilter-name>
    7. <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    8. <init-param>
    9. <param-name>encodingparam-name>
    10. <param-value>UTF-8param-value>
    11. init-param>
    12. <init-param>
    13. <param-name>forceEncodingparam-name>
    14. <param-value>trueparam-value>
    15. init-param>
    16. filter>
    17. <filter-mapping>
    18. <filter-name>CharacterEncodingFilterfilter-name>
    19. <url-pattern>/*url-pattern>
    20. filter-mapping>
    21. <filter>
    22. <filter-name>HiddenHttpMethodFilterfilter-name>
    23. <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
    24. filter>
    25. <filter-mapping>
    26. <filter-name>HiddenHttpMethodFilterfilter-name>
    27. <url-pattern>/*url-pattern>
    28. filter-mapping>
    29. <servlet>
    30. <servlet-name>DispatcherServletservlet-name>
    31. <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    32. <init-param>
    33. <param-name>contextConfigLocationparam-name>
    34. <param-value>classpath:SpringMVC.xmlparam-value>
    35. init-param>
    36. <load-on-startup>1load-on-startup>
    37. servlet>
    38. <servlet-mapping>
    39. <servlet-name>DispatcherServletservlet-name>
    40. <url-pattern>/url-pattern>
    41. servlet-mapping>
    42. <listener>
    43. <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    44. listener>
    45. <context-param>
    46. <param-name>contextConfigLocationparam-name>
    47. <param-value>classpath:Spring.xmlparam-value>
    48. context-param>
    49. web-app>

    1.3 SpringMVC.xml

    1. <beans xmlns="http://www.springframework.org/schema/beans"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
    3. xmlns:context="http://www.springframework.org/schema/context"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
    5. <context:component-scan base-package="ssm.controller"/>
    6. <bean id="viewResolver"
    7. class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
    8. <property name="order" value="1"/>
    9. <property name="characterEncoding" value="UTF-8"/>
    10. <property name="templateEngine">
    11. <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
    12. <property name="templateResolver">
    13. <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
    14. <property name="prefix" value="/WEB-INF/templates/"/>
    15. <property name="suffix" value=".html"/>
    16. <property name="templateMode" value="HTML5"/>
    17. <property name="characterEncoding" value="UTF-8" />
    18. bean>
    19. property>
    20. bean>
    21. property>
    22. bean>
    23. <mvc:default-servlet-handler />
    24. <mvc:annotation-driven />
    25. <mvc:view-controller path="/" view-name="index"/>
    26. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
    27. beans>

    1.4 Spring.xml

     

    1. <beans xmlns="http://www.springframework.org/schema/beans"
    2. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    4. xsi:schemaLocation="http://www.springframework.org/schema/beans
    5. http://www.springframework.org/schema/beans/spring-beans.xsd
    6. http://www.springframework.org/schema/context
    7. https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    8. <context:component-scan base-package="ssm">
    9. <context:exclude-filter type="annotation"
    10. expression="org.springframework.stereotype.Controller"/>
    11. context:component-scan>
    12. <context:property-placeholder location="classpath:jdbc.properties"/>
    13. <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    14. <property name="driverClassName" value="${jdbc.driver}"/>
    15. <property name="url" value="${jdbc.url}"/>
    16. <property name="username" value="${jdbc.username}"/>
    17. <property name="password" value="${jdbc.password}"/>
    18. bean>
    19. <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    20. <property name="dataSource" ref="dataSource"/>
    21. bean>
    22. <tx:annotation-driven transaction-manager="transactionManager"/>
    23. <bean class="org.mybatis.spring.SqlSessionFactoryBean">
    24. <property name="configLocation" value="classpath:mybatis-config.xml"/>
    25. <property name="dataSource" ref="dataSource"/>
    26. <property name="typeAliasesPackage" value="ssm.pojo"/>
    27. bean>
    28. <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    29. <property name="basePackage" value="ssm.mapper"/>
    30. bean>
    31. beans>

    1.5 mybatis-config.xml

            有一些参数已经在spring配置文件里进行配置了。

    1. configuration
    2. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
    4. <configuration>
    5. <settings>
    6. <setting name="mapUnderscoreToCamelCase" value="true"/>
    7. settings>
    8. <plugins>
    9. <plugin interceptor="com.github.pagehelper.PageInterceptor"/>
    10. plugins>
    11. configuration>

    1.6 log4j.xml

    1. log4j:configuration SYSTEM "log4j.dtd">
    2. <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    3. <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
    4. <param name="Encoding" value="UTF-8"/>
    5. <layout class="org.apache.log4j.PatternLayout">
    6. <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS}
    7. %m (%F:%L) \n"/>
    8. layout>
    9. appender>
    10. <logger name="java.sql">
    11. <level value="debug"/>
    12. logger>
    13. <logger name="org.apache.ibatis">
    14. <level value="info"/>
    15. logger>
    16. <root>
    17. <level value="debug"/>
    18. <appender-ref ref="STDOUT"/>
    19. root>
    20. log4j:configuration>

    1.7 jdbc.properties

    1. jdbc.username=root
    2. jdbc.password=310333
    3. jdbc.url=jdbc:mysql://localhost:3306/ssm_demodb?serverTimezone=UTC
    4. jdbc.driver=com.mysql.cj.jdbc.Driver

    二、分页插件PageHelper

    2.1 配置

            依赖:

    1. <dependency>
    2. <groupId>com.github.pagehelpergroupId>
    3. <artifactId>pagehelperartifactId>
    4. <version>5.2.0version>
    5. dependency>

            在MyBatis的核心配置文件中配置插件:

    1. <plugins>
    2. <plugin interceptor="com.github.pagehelper.PageInterceptor">plugin>
    3. plugins>

    2.2 使用

            1.在查询功能之前使用PageHelper.startPage(int pageNum, int pageSize)开启分页功能

            pageNum:当前页的页码

            pageSize:每页显示的条数 

            2.在查询获取list集合之后,使用PageInfo pageInfo = new PageInfo<>(List list, int navigatePages)获取分页相关数据  。

            list:分页之后的数据

            navigatePages:导航分页的页码数

             3.分页相关数据

    list:查询到的数据

    pageNum:当前页的页码

    pageSize:每页显示的条数

    size:当前页显示的真实条数

    total:总记录数

    pages:总页数

    prePage:上一页的页码

    nextPage:下一页的页码

    isFirstPage/isLastPage:是否为第一页/最后一页

    hasPreviousPage/hasNextPage:是否存在上一页/下一页

    navigatePages:导航分页的页码数

    navigatepageNums:导航分页的页码,[1,2,3,4,5]

    2.3 Demo

            数据库表:

    1. CREATE TABLE `t_emp` (
    2. `emp_id` int(11) NOT NULL AUTO_INCREMENT,
    3. `emp_name` varchar(20) DEFAULT NULL,
    4. `age` int(11) DEFAULT NULL,
    5. `sex` char(1) DEFAULT NULL,
    6. `email` varchar(50) DEFAULT NULL,
    7. PRIMARY KEY (`emp_id`)
    8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8

            pojo:

    1. package ssm.pojo;
    2. public class Employee {
    3. private Integer empId;
    4. private String empName;
    5. private Integer age;
    6. private String sex;
    7. private String email;
    8. public Employee() {
    9. }
    10. public Employee(Integer empId, String empName, Integer age, String sex,
    11. String email) {
    12. this.empId = empId;
    13. this.empName = empName;
    14. this.age = age;
    15. this.sex = sex;
    16. this.email = email;
    17. }
    18. public Integer getEmpId() {
    19. return empId;
    20. }
    21. public void setEmpId(Integer empId) {
    22. this.empId = empId;
    23. }
    24. public String getEmpName() {
    25. return empName;
    26. }
    27. public void setEmpName(String empName) {
    28. this.empName = empName;
    29. }
    30. public Integer getAge() {
    31. return age;
    32. }
    33. public void setAge(Integer age) {
    34. this.age = age;
    35. }
    36. public String getSex() {
    37. return sex;
    38. }
    39. public void setSex(String sex) {
    40. this.sex = sex;
    41. }
    42. public String getEmail() {
    43. return email;
    44. }
    45. public void setEmail(String email) {
    46. this.email = email;
    47. }
    48. }

            Controller:

    1. @Controller
    2. public class EmployeeController {
    3. @Autowired
    4. private EmployeeService employeeService;
    5. /*查询所有员工信息(分页)*/
    6. @RequestMapping(value = "/employee/page/{pageNum}",method = RequestMethod.GET)
    7. public String getEmployeePage(@PathVariable("pageNum") Integer pageNum,Model model){
    8. PageInfo page=employeeService.getEmployeePage(pageNum);//获取分页数据
    9. model.addAttribute("page",page);//将分页数据保存到域中
    10. return "employee_list";//转至员工列表页面
    11. }
    12. }

             Service:

    1. public class EmployeeServiceImpl implements EmployeeService {
    2. @Autowired
    3. private EmployeeMapper employeeMapper;
    4. //获取所有员工信息
    5. @Override
    6. public List getAllEmployee() {
    7. return employeeMapper.getAllEmployee();
    8. }
    9. //获取所有员工信息的分页信息
    10. @Override
    11. public PageInfo getEmployeePage(Integer pageNum) {
    12. //开启分页功能,每页显示4条数据
    13. PageHelper.startPage(pageNum,4);
    14. //查询所有员工信息
    15. List list=employeeMapper.getAllEmployee();
    16. //获取分页相关数据
    17. return new PageInfo(list,5); //导航页显示5页
    18. }
    19. }

            Mapper:

    1. public interface EmployeeMapper {
    2. List getAllEmployee();
    3. }
    1. <mapper namespace="ssm.mapper.EmployeeMapper">
    2. <select id="getAllEmployee" resultType="Employee">
    3. select * from t_emp
    4. select>
    5. mapper>

            employee_list页面(index页面自行设置):

    1. html>
    2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>员工列表title>
    6. head>
    7. <body>
    8. <div align="center">
    9. <table border="1" cellspacing="0" >
    10. <tr>
    11. <th colspan="6">员工信息th>
    12. tr>
    13. <tr>
    14. <th>流水号th>
    15. <th>姓名th>
    16. <th>年龄th>
    17. <th>性别th>
    18. <th>邮箱th>
    19. <th>操作th>
    20. tr>
    21. <tr th:each="employee,status : ${page.list}">
    22. <td th:text="${status.count}">td>
    23. <td th:text="${employee.empName}">td>
    24. <td th:text="${employee.age}">td>
    25. <td th:text="${employee.sex}">td>
    26. <td th:text="${employee.email}">td>
    27. <td>
    28. <a href="">删除a>
    29. <a href="">修改a>
    30. td>
    31. tr>
    32. table>
    33. div>
    34. <div align="center">
    35. <a th:if="${page.hasPreviousPage}" th:href="@{/employee/page/1}">首页a>
    36. <a th:if="${page.hasPreviousPage}" th:href="@{'/employee/page/'+${page.prePage}}">上一页a>
    37. <span th:each="num:${page.navigatepageNums}">
    38. <a th:if="${page.pageNum!=num}" th:href="@{'/employee/page/'+${num}}" th:text="${num}">a>
    39. <span th:if="${page.pageNum==num}" style="color:red " th:text="'['+${num}+']'">span>
    40. span>
    41. <a th:if="${page.hasNextPage}" th:href="@{'/employee/page/'+${page.nextPage}}">下一页a>
    42. <a th:if="${page.hasNextPage}" th:href="@{'/employee/page/'+${page.pages}}">末页a>
    43. div>
    44. body>
    45. html>

            效果:

     

  • 相关阅读:
    C语言文件操作
    SpringBoot 入门
    【推荐系统】推荐系统基础算法-基于矩阵分解的推荐方法、隐语义模型
    利用IBERT IP核实现GTX收发器硬件误码率测试实例
    多模态模型
    React 入门:组件实例三大属性之refs
    YOLOv5小目标检测(方法与评价)
    python 数字类型
    Python中json.loads()无法解析单引号字符串问题的两种解决方法
    kubernetes集成GPU原理
  • 原文地址:https://blog.csdn.net/weixin_62427168/article/details/126082035