SSM-CRUD 的环境搭建,包含逆向工程及分页,每一步代码都有解释,很详细

@一榔捶

一、SSM—CRUD

1、项目简介

  • 分页(pageHelper)
  • 数据校验:jquery前端校验,JSR303后段校验
  • ajax
  • Rest风格的URL

2、技术点

  • 基础框架-SSM(Spring + SpringMVC + MyBatis)
  • 数据库(MySQL)
  • 前端框架(bootStrap)
  • 项目的依赖管理(Maven)
  • 分页(pagehelper)
  • 逆向工程(MyBatis Generator)

3、基础环境的搭建

(1)、创建一个基础的maven工程,并引入项目依赖的jar包

pom.xml包如下

  • Spring(webMVC、jdbc、aspects、test)、SpringMVC、MyBatis为5.3.1版本
  • MyBatis-Spring整合包2.0.1版本
  • thymelef3.0.11
  • MBG(逆向工程 )mybatis-generator-core 1.3.7
<!--    引入SppringMVC、Spring-->
    <dependencies>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.1</version>
        </dependency>
<!--        Spring-jdbc-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.1</version>
        </dependency>
<!--Spring Aspect面向切面-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.3.1</version>
        </dependency>
<!--mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.1</version>
        </dependency>
<!--mybatis整合spring-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.1</version>
        </dependency>
<!--数据库连接池、驱动-->
        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
<!--jstl,servlet-api,junit-->
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.11.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.thymeleaf/thymeleaf-spring5 -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
            <version>3.0.12.RELEASE</version>
        </dependency>
<!--        MBG逆向工程-->
        <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core -->
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.7</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.3.1</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
(2)、引入 BootStrap 前端框架和 Jquery

使用

<%--
  Created by IntelliJ IDEA.
  User: ban
  Date: 2021/11/17
  Time: 20:14
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
<%--    引入jquery--%>
    <script type="text/javascript" src="static/js/jquery-1.12.4.min.js"></script>
<%--    引入样式--%>
    <link href="static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <title>$Title$</title>
  </head>
  <body>
      <button class="glyphicon-cloud">按钮</button>
  </body>
</html>
(3)、配置web.xml

Spring容器的启动(applicationContext.xml作为Spring的配置文件)

	<!--1、启动Spring的容器  -->
	<!-- needed for ContextLoaderListener -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>

	<!-- Bootstraps the root web application context before servlet initialization -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

SpringMVC文件的配置(SpringMVC.xml 作为SpringMVC的配置文件)

<!--	放在最前面-->
	<filter>
		<filter-name>CharacterEncodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceResponseEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CharacterEncodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- 使用Rest风格的URI,将页面普通的post请求转为指定的delete或者put请求 -->
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!--前段控制器-->
	<servlet>
		<servlet-name>SpringMVC</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>SpringMVC</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
(4)、配置SpringMVC.xml

扫描的开启,设定为只扫描Controller组件

配置Thymelef视图解析器

mvc两个标签的开启

<!--    只扫描Controller,其他不扫描,并关闭默认扫描-->
    <context:component-scan base-package="com.ban" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--    thymeleaf-->
    <!-- 配置Thymeleaf视图解析器 -->
    <bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
        <property name="order" value="1"/>
        <property name="characterEncoding" value="UTF-8"/>
        <property name="templateEngine">
            <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                <property name="templateResolver">
                    <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                        <!-- 视图前缀 -->
                        <property name="prefix" value="WEB-INF/templates/"/>
                        <!-- 视图后缀 -->
                        <property name="suffix" value=".html"/>
                        <property name="templateMode" value="HTML5"/> <property name="characterEncoding" value="UTF-8" />
                    </bean>
                </property>
            </bean>
        </property>
    </bean>

<!--    将SpringMVC不能处理的请求交给tomcat-->
    <mvc:default-servlet-handler/>
<!--    能支持SPringMVC更高级的一些功能,映射动态请求-->
    <mvc:annotation-driven/>
(5)、配置Spring

jdbc数据源的配置

jdbc.properties

jdbc.username=root
jdbc.password=374761727
jdbc.url=jdbc:mysql://localhost:3306/ssm_crud?characterEncoding=utf8
jdbc.driverClassName=com.mysql.cj.jdbc.Driver

applicationContext.xml中对数据源的配置(使用C3P0)

    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--    配置jdbc-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="driverClass" value="${jdbc.driverClassName}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>

applicationContext.xml文件中对mybatis的整合、扫描的开启、以及事务控制的配置

<!--    开启扫描,除了Controller不扫描其他都扫描-->
    <context:component-scan base-package="com.ban">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

配置和MyBatis的整合

其中 mapperLocations 需要和 MyBatis 的配置文件整合使用

<bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="dataSource" ref="dataSource"></property>
<!--        指定MyBatis-Mapper文件的位置-->
        <property name="mapperLocations" value="classpath*:mapper/*Mapper.xml"></property>
    </bean>
<!--    配置扫描器,将myBatis接口的实现加入到ioc容器中-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--            扫描dao接口的实现,加入到ioc容器中-->
            <property name="basePackage" value="com.ban.crud.dao"></property>
        </bean>

事务控制的配置

    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
<!--    开启基于注解的事务,使用xml配置形式的事务-->
    <aop:config>
<!--        切入点表达式-->
        <aop:pointcut id="txPoint" expression="execution(* com.ban.crud.service..* (..))"/>
<!--        配置事务增强-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"></aop:advisor>
    </aop:config>
<!--    配置事务增强,事务如何切入,tx:tx-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
<!--        所有方法都是事务方法-->
        <tx:method name="*"/>
<!--        所有的get方法都是事务方法 -->
        <tx:method name="get*" read-only="true"/>
    </tx:attributes>
</tx:advice>
applicationContext的整合
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

<!--    开启扫描,除了Controller不扫描其他都扫描-->
    <context:component-scan base-package="com.ban">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
<!--===========================================数据源===========================================-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--    配置jdbc-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="driverClass" value="${jdbc.driverClassName}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>
<!--===========================================配置和MyBatis的整合===========================================-->
    <bean id="SqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="dataSource" ref="dataSource"></property>
<!--        指定MyBatis-Mapper文件的位置-->
        <property name="mapperLocations" value="classpath*:mapper/*Mapper.xml"></property>
    </bean>
<!--    配置扫描器,将myBatis接口的实现加入到ioc容器中-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--            扫描dao接口的实现,加入到ioc容器中-->
            <property name="basePackage" value="com.ban.crud.dao"></property>
        </bean>
<!--===========================================事务控制的配置===========================================-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
<!--    开启基于注解的事务,使用xml配置形式的事务-->
    <aop:config>
<!--        切入点表达式-->
        <aop:pointcut id="txPoint" expression="execution(* com.ban.crud.service..* (..))"/>
<!--        配置事务增强-->
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"></aop:advisor>
    </aop:config>
<!--    配置事务增强,事务如何切入,tx:tx-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
<!--        所有方法都是事务方法-->
        <tx:method name="*"/>
<!--        所有的get方法都是事务方法 -->
        <tx:method name="get*" read-only="true"/>
    </tx:attributes>
</tx:advice>
</beans>

4、配置MyBatis

其中 标签配合 Spring 配置文件中和MyBatis整合模块中的mapperLocations进行配合使用

<?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>
<!--    <settings>-->
<!--        <setting name="mapUnderscoreToCamelCase" value="true"/>-->
<!--    </settings>-->
		<mappers>
        <package name="com.ban.crud.dao"/>
<!--        <mapper resource="DepartmentMapper.xml"></mapper>-->
    </mappers>
</configuration>

数据库文件的配置(tbl_emp)

主键自增非空且 d_id 作为 tbl_dept 表中 dept_id 列的外键

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qKHduL46-1674479470062)(/Users/ban/Library/Application Support/typora-user-images/image-20211120125411930.png)]

tbl_dept[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fNiDQwuq-1674479470063)(/Users/ban/Library/Application Support/typora-user-images/image-20211120125451400.png)]

5、配置MBG逆向工程

配置MBG.xml文件(官网文档)

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>


<!--    targetRuntime: 生成策略 MyBatis3Simple: 简单版的CRUD MyBatis3: 豪华版的CRUD, 支持QBC⻛格-->
    <context id="mybatisGenerator" targetRuntime="MyBatis3">
      
<!--        没有注释的语句-->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
      
        <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver"                        											connectionURL="jdbc:mysql://localhost:3306/ssm_crud?characterEncoding=utf8"
                        userId="root"
                        password="374761727">
        </jdbcConnection>
      
        <!-- 默认false,把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer,为 true时把JDBC DECIMAL 和NUMERIC 类型解析为java.math.BigDecimal -->
        <javaTypeResolver>
        <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>

        <!-- targetProject:生成POJO类的位置 -->
        <javaModelGenerator
            targetPackage="com.ban.crud.bean"
            targetProject="./src/main/java">
        <!-- enableSubPackages:是否让schema作为包的后缀 -->
        <property name="enableSubPackages" value="false" /> <!-- 从数据库返回的值被清理前后的空格 -->
        <property name="trimStrings" value="true" />
        </javaModelGenerator>

        <!-- targetProject:mapper映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="mapper"
                         targetProject="./src/main/resources/">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
        <property name="enableSubPackages" value="false" />
        </sqlMapGenerator>

        <!-- targetPackage:mapper接口生成的位置 -->
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.ban.crud.dao"
                             targetProject="./src/main/java">
            <!-- enableSubPackages:是否让schema作为包的后缀 -->
        <property name="enableSubPackages" value="false" />
        </javaClientGenerator>
        <!-- 指定数据库表 -->
        <table tableName="tbl_emp" domainObjectName="Employee"></table>
        <table tableName="tbl_dept" domainObjectName="Department"></table>
    </context>
</generatorConfiguration>

MBG测试文件进行生成 Bean、Dao、Mapper 类文件(官方文档)

public class MgbTest {
    @Test
    public void test1() throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException {
        List<String> warnings = new ArrayList<String>();
        boolean overwrite = true;
        File configFile = new File("./src/main/java/mbg.xml");
        ConfigurationParser cp = new ConfigurationParser(warnings);
        Configuration config = cp.parseConfiguration(configFile);
        DefaultShellCallback callback = new DefaultShellCallback(overwrite);
        MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
        myBatisGenerator.generate(null);
    }
}
//运行结束后根据数据库的情况生成了Bean、Dao、Mapper文件

6、Mapper文件的修改

EmployeeMapper接口的修改

    /**
     * 新加的查询部门信息
     * @param example
     * @return
     */
    List<Employee> selectByExampleWithDept(EmployeeExample example);

    Employee selectByPrimaryKeyWithDept(Integer empId);

EmployeeMapper.xml文件的修改

  <resultMap id="BaseResultMap" type="com.ban.crud.bean.Employee">
    <id column="emp_id" jdbcType="INTEGER" property="empId" />
    <result column="emp_name" jdbcType="VARCHAR" property="empName" />
    <result column="gender" jdbcType="CHAR" property="gender" />
    <result column="email" jdbcType="VARCHAR" property="email" />
    <result column="d_id" jdbcType="INTEGER" property="dId" />
  </resultMap>
  <resultMap id="WithDeptResultMap" type="com.ban.crud.bean.Employee">
    <id column="emp_id" jdbcType="INTEGER" property="empId" />
    <result column="emp_name" jdbcType="VARCHAR" property="empName" />
    <result column="gender" jdbcType="CHAR" property="gender" />
    <result column="email" jdbcType="VARCHAR" property="email" />
    <result column="d_id" jdbcType="INTEGER" property="dId" />
    <association property="department" javaType="com.ban.crud.bean.Department">
      <id column="dept_id" property="deptId"/>
      <result column="dept_name" property="deptName"/>
    </association>
  </resultMap>

<!--  List<Employee> selectByExampleWithDept(EmployeeExample example);-->
  <select id="selectByExampleWithDept" resultMap="WithDeptResultMap">
  <if test="distinct">
    distinct
  </if>
  <include refid="WithDept_Column_List" />
  FROM tbl_emp e
    left join tbl_dept d on e.`d_id` = d.`dept_id`
  <if test="_parameter != null">
    <include refid="Example_Where_Clause" />
  </if>
  <if test="orderByClause != null">
    order by ${orderByClause}
  </if>
</select>
<!--  Employee selectByPrimaryKeyWithDept(Integer empId);-->
  <select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap">

    select
    <include refid="WithDept_Column_List" />
    from tbl_emp e
    left join tbl_dept d  on e.`d_id`=d.`dept_id`
    where emp_id = #{empId,jdbcType=INTEGER}
  </select>

7、搭建Spring-Test环境

/**
 * 1、导入SpringTest模块(Pom)
 * 2、@ContextConfiguration指定Spring配置文件的位置
 * 3、RunWith使用@RunWith(SpringJUnit4ClassRunner.class)
 */
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class CRUDTest {

    @Autowired
    DepartmentMapper departmentMapper;
    @Test
    public void testCrud(){
        System.out.println(departmentMapper);
        departmentMapper.insertSelective(new Department(1,"开发"));
    }
//org.apache.ibatis.binding.MapperProxy@4ed5eb72
jdbc:mysql://localhost:3306/ssm_crud?characterEncoding=utf8

8、配置一个可批量执行的sqlSession

applicationContext.xml文件的配置

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="SqlSessionFactoryBean"/>
<!--        默认不是BATCH,需要将其配置为批量的-->
        <constructor-arg name="executorType" value="BATCH"/>
    </bean>

其中@Autowired将sqlSession注入,因为SqlSessionTemplate实现了SqlSession

@Autowired
  SqlSession sqlSession;

	@Test
    public void testCrud(){
        System.out.println(departmentMapper);
//        departmentMapper.insertSelective(new Department(null,"商业"));
//        employeeMapper.insertSelective(new Employee(null,"zhangsan","M","10086@sina.com",1));
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        long start = System.currentTimeMillis();
        for(int i = 0 ; i < 1000 ; i++){
            String uid = UUID.randomUUID().toString().substring(0, 5)+i;
            mapper.insertSelective(new Employee(null,uid,"M",uid+"10086@sina.com",1));
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start);
        System.out.println("批量完成");
    }

二、查询功能的实现

1、分页后台部分代码的实现

借助pageHelper

EmployeeController

    /**
     *
     * 查询员工数据(分页查询)
     * @return
     */
    //@RequestMapping("/emps")
    //页码默认为第一页
    public String getEmps(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum, Model model){
        //使用pageHelper分页插件
        //查询之前只需要调用从第几页开始,每一页显示几条数据
        PageHelper.startPage(pageNum,5);
        //startPage后面紧跟着的这个查询就是一个分页查询
        List<Employee> emps = employeeService.getAll();
        //使用pageInfo包装查询后的结果,只需要将pageInfo交给页面即可
        //封装类详细的分页信息,包括我们查询出来的数据,传入连续显示的参数(即从传入的页面之后几页)
        PageInfo pageInfo = new PageInfo(emps, 5);
        model.addAttribute("pageInfo",pageInfo);
        return "list";
    }

2、测试通过pageHelper的数据

MvcTest

/**
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration(value = "/web")
@ContextConfiguration(locations = {"classpath:applicationContext.xml","classpath:SpringMVC.xml"})
public class MvcTest {
    //传入SpringMVC的ioc
    @Autowired
    WebApplicationContext context;
    //模拟mvc请求,获取到处理结果

    MockMvc mockMvc;

    @Before
    public void initMokcMvc(){
       mockMvc= MockMvcBuilders.webAppContextSetup(context).build();
    }
    @Test
    public void testPage() throws Exception {
        //模拟请求并得到返回值
        MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/emps").param("pageNum", "1")).andReturn();
        //请求成功后,请求域中会有pageInfo:我们可以取出pageInfo进行验证
        MockHttpServletRequest request = result.getRequest();
        PageInfo pageNum = (PageInfo) request.getAttribute("pageInfo");
        System.out.println("当前页码"+pageNum.getPageNum());
        System.out.println("总页码"+pageNum.getPages());
        System.out.println("总记录数量"+pageNum.getTotal());
        System.out.println("需要连续显示的页码");
        int[] nums=pageNum.getNavigatepageNums();
        for(int i :nums){
            System.out.println(" "+i);
        }
        //获取员工数据
        List<Employee> list = pageNum.getList();
                for(Employee employee : list){
                    System.out.println("ID:"+employee.getEmpId()+"Name:"+employee.getEmpName()+"email:"+employee.getEmail()+"gender:"+employee.getGender()+"dId:"+employee.getdId());
                }

    }
}

3、搭建Bootstrap页面

根据Bootstrap官方文档进行编写

list.jsp

<%--
  Created by IntelliJ IDEA.
  User: ban
  Date: 2021/11/20
  Time: 19:37
  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</title>
<%--    以 / 开始,不以 / 结束--%>
    <%
        pageContext.setAttribute("APP_PATH",request.getContextPath());
    %>
<%--    web不以/开始的相对路径,找资源,以当前资源的路径为基准,经常容易出问题
以/开始的相对路径,找资源,以服务器的路径为标准(http://loaclhost:3306)需要加上项目名



--%>
        <script type="text/javascript" src="${APP_PATH}/static/js/jquery-1.12.4.min.js"></script>
    <%--    引入样式--%>
        <link href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
        <script src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
    <div class="container">
<%--        标题--%>
        <div class="row">
            <div class="col-md-12">
                <h1>SSM-CRUD-ZYL</h1>
            </div>
        </div>
<%--    功能按钮--%>
        <div class="row">
            <div class="col-md-4 col-md-offset-8">
                <button class="btn btn-primary">新增</button>
                <button class="btn btn-danger">删除</button>
            </div>
        </div>
<%--    显示表格数据--%>
        <div class="row">
            <div class="col-md-12">
                <table class="table table-hover">
                    <tr>
                        <th>#</th>
                        <th>empName</th>
                        <th>gender</th>
                        <th>email</th>
                        <th>deptName</th>
                        <th>操作</th>
                    </tr>
                    <c:forEach items="${pageInfo.list}" var="emp">
                        <tr>
                            <th>${emp.empId}</th>
                            <th>${emp.empName}</th>
                            <th>${emp.gender=="M"?"男":"女"}</th>
                            <th>${emp.email}</th>
                            <th>${emp.department.deptName}</th>
                            <th>
                                <button class="btn btn-primary btn-sm">编辑
                                    <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
                                </button>
                                <button class="btn btn-danger btn-sm">删除
                                    <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
                                </button>
                            </th>
                        </tr>
                    </c:forEach>

                </table>
            </div>
        </div>
<%--    显示分页信息--%>
        <div class="row">
<%--            分页文字信息--%>
            <div class="col-md-6">
                当前${pageInfo.pageNum}页,总${pageInfo.pages}页,总${pageInfo.total}条记录,
            </div>
<%--            分页条信息--%>
            <div class="col-md-6">
                <nav aria-label="Page navigation">
                    <ul class="pagination">
                        <li><a href="${APP_PATH}/emps?pageName=1">首页</a></li>
<%--====================判断上一页的条件==========================================--%>
                        <c:if test="${pageInfo.hasPreviousPage}">
<%--                        上一页--%>
                            <li>
                                <a href="${APP_PATH}/emps?pageNum=${pageInfo.pageNum-1}" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                        </c:if>
<%--====================判断上一页的条件==========================================--%>


<%--                        如果是当前页码,显示为高亮,并为每一个页码赋给链接--%>
<%--                        page_num是需要连续显示的页码--%>
                        <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="${APP_PATH}/emps?pageNum=${page_num}">${page_num}</a></li>
                            </c:if>
                        </c:forEach>

<%--====================判断下一页的条件==========================================--%>
                        <c:if test="${pageInfo.hasNextPage}">
                            <li>
                                <a href="${APP_PATH}/emps?pageNum=${pageInfo.pageNum+1}" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        </c:if>
<%--====================判断下一页的条件==========================================--%>
                        <li><a href="${APP_PATH}/emps?pageNum=${pageInfo.pages}">末页</a></li>
                    </ul>
                </nav>
            </div>
        </div>
    </div>

</body>
</html>

4、返回分页的json数据(对以上进行更改)

Msg:作为信息返回

public class Msg {
    //状态吗 100-成功 200-失败
    private int code;
    //提示信息
    private String msg;
    //用户要返回给浏览器的数据
    private Map<String,Object> extend = new HashMap<String,Object>();

    public static Msg success(){
        Msg result = new Msg();
        result.setCode(100);
        result.setMsg("处理成功!");
        return result;
    }
    public static Msg fail(){
        Msg result = new Msg();
        result.setCode(200);
        result.setMsg("处理失败!");
        return result;
    }
    public Msg add(String key,Object value){
        this.getExtend().put(key,value);
        return this;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Map<String, Object> getExtend() {
        return extend;
    }

    public void setExtend(Map<String, Object> extend) {
        this.extend = extend;
    }
}

EmployeeController

返回分页的json数据

@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    //将pageInfo以json形式返回,需要导入jackson包才可以将pageInfo转换为json字符串
    @RequestMapping("/emps")
    @ResponseBody
    public Msg getEmpsWithJson(@RequestParam(value = "pageNum",defaultValue = "1")Integer pageNum){
        PageHelper.startPage(pageNum,5);
        //startPage后面紧跟着的这个查询就是一个分页查询
        List<Employee> emps = employeeService.getAll();
        //使用pageInfo包装查询后的结果,只需要将pageInfo交给页面即可
        //封装类详细的分页信息,包括我们查询出来的数据,传入连续显示的参数(即从传入的页面之后几页)
        PageInfo pageInfo = new PageInfo(emps, 5);
        return Msg.success().add("pageInfo",pageInfo);
    }

根据返回的json数据进行jsp文件重构

ajax、jquery

分页部分的实现

<%--
  Created by IntelliJ IDEA.
  User: ban
  Date: 2021/11/20
  Time: 19:37
  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</title>
    <%--    以 / 开始,不以 / 结束--%>
    <%
        pageContext.setAttribute("APP_PATH",request.getContextPath());
    %>
    <%--    web不以/开始的相对路径,找资源,以当前资源的路径为基准,经常容易出问题
    以/开始的相对路径,找资源,以服务器的路径为标准(http://loaclhost:3306)需要加上项目名



    --%>
    <script type="text/javascript" src="${APP_PATH}/static/js/jquery-1.12.4.min.js"></script>
    <%--    引入样式--%>
    <link href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
    <%--        标题--%>
    <div class="row">
        <div class="col-md-12">
            <h1>SSM-CRUD-ZYL</h1>
        </div>
    </div>
    <%--    功能按钮--%>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button class="btn btn-primary">新增</button>
            <button class="btn btn-danger">删除</button>
        </div>
    </div>
    <%--    显示表格数据--%>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-hover" id="emps_table">
                <tr>
                    <th>#</th>
                    <th>empName</th>
                    <th>gender</th>
                    <th>email</th>
                    <th>deptName</th>
                    <th>操作</th>
                </tr>
            </table>
        </div>
    </div>
    <%--    显示分页信息--%>
    <div class="row">
        <%--            分页文字信息--%>
        <div class="col-md-6" id="page_info_area">
        </div>
        <%--            分页条信息--%>
        <div class="col-md-6" id="page_nav_area">
        </div>
    </div>
</div>

<script type="text/javascript">
    $(function () {
        //默认为首页
       to_page(1);
    });
    //解析table框中的信息
    function build_emps_table(result){
        //清空table表格
        $("#emps_table tbody").empty();
        var emps = result.extend.pageInfo.list;
        $.each(emps,function (index,item){
            //根据jsp页面的结构进行构建
            var empIdTd = $("<td></td>").append(item.empId);
            var empNameTd = $("<td></td>").append(item.empName);
            var genderTd = $("<td></td>").append(item.gender=='M'?'男':'女');
            var emailTd = $("<td></td>").append(item.email);
            var deptNameTd = $("<td></td>").append(item.department.deptName);
            /*
            * <button class="btn btn-danger btn-sm">删除
                                    <span class="glyphicon glyphicon-trash" aria-hidden="true"></span>
                                </button>
            * */
            var editBtn = $("<button></button>").addClass("btn btn-primary btn-sm").append($("<span></span>").addClass("glyphicon glyphicon-pencil")).append("编辑")
            var delBtn = $("<button></button>").addClass("btn btn-danger btn-sm").append($("<span></span>").addClass("glyphicon glyphicon-trash")).append("删除")
            var btnTd = $("<td></td>").append(editBtn).append(" ").append(delBtn);
            //append方法执行完成以后还是返回原来的元素
            $("<tr></tr>").append(empIdTd).append(empNameTd).append(genderTd).append(emailTd).append(deptNameTd)
                .append(btnTd).appendTo("#emps_table tbody");
        })}
        //解析显示分页信息
    function build_page_info(result){
        $("#page_info_area").empty()
        $("#page_info_area").append("当前"+result.extend.pageInfo.pageNum+"页,总"+result.extend.pageInfo.pages+"页,总"+result.extend.pageInfo.total+"条记录");
    }
    //解析显示分页条数据
    function build_page_nav(result){
        /*
        <nav aria-label="Page navigation">
        <ul class="pagination">
        <li>
      <a href="#" aria-label="Previous">
        <span aria-hidden="true">&laquo;</span>
      </a>
    </li>
    <li><a href="#">1</a></li>
    * */
        $("#page_nav_area").empty()
        var ul = $("<ul></ul>").addClass("pagination");
        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href","#"))
        var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"))
        if(result.extend.pageInfo.hasPreviousPage == false){
           firstPageLi.addClass("disabled");
           prePageLi.addClass("disabled");
        }else{
            //首页的跳转
            firstPageLi.click(function () {
                to_page(1)
            })

            //上一页的跳转
            prePageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum-1);
            })
        }

        var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;"))
        var lastPageLi = $("<li></li>").append($("<a></a>").append("末页").attr("href","#"))
        if(result.extend.pageInfo.hasNextPage == false){
            nextPageLi.addClass("disabled");
            lastPageLi.addClass("disabled");
        }else{
            //下一页的跳转
            nextPageLi.click(function () {
                to_page(result.extend.pageInfo.pageNum+1)
            })

            //末页的跳转
            lastPageLi.click(function () {
                to_page(result.extend.pageInfo.pages)
            })
        }
        //添加首页和前一页的模块
        ul.append(firstPageLi).append(prePageLi);
        //遍历1,2,3给ul中添加页码提示
        $.each(result.extend.pageInfo.navigatepageNums,function (index,item) {

            var numLi = $("<li></li>").append($("<a></a>").append(item))
            if(result.extend.pageInfo.pageNum == item){
                numLi.addClass("active");
            }
            numLi.click(function () {
                to_page(item)
            })
            ul.append(numLi);
        });
        //添加下一页和末页的提示
        ul.append(nextPageLi).append(lastPageLi);
        //把ul加入到nav中
        var navEle = $("<nav></nav>").append(ul);
        navEle.appendTo("#page_nav_area");
    }
    //页码跳转模组
    function to_page(pageNum){
        $.ajax({
            url:"${APP_PATH}/emps",
            data:"pageNum="+pageNum,
            type:"GET",
            success:function (result) {
                build_emps_table(result);
                build_page_info(result);
                build_page_nav(result);
            }
        })
    }
</script>
</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值