四、SSM整合案例
1、ContextLoaderListener
Spring提供了监听器ContextLoaderListener,实现ServletContextListener接口,可监听 ServletContext的状态,在web服务器的启动,读取Spring的配置文件,创建Spring的IOC容器。web 应用中必须在web.xml中配置
<listener> <!-- 配置Spring的监听器,在服务器启动时加载Spring的配置文件 Spring配置文件默认位置和名称:/WEB-INF/applicationContext.xml 可通过上下文参数自定义Spring配置文件的位置和名称 --> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--自定义Spring配置文件的位置和名称--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param>
2、案例一
2.1、准备工作
① 创建Maven Module
② 引入项目依赖
<?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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jingchao</groupId> <artifactId>ssm</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <spring.version>5.3.18</spring.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <!-- SpringMVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- MyBatis核心 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.10</version> </dependency> <!-- MyBatis和Spring的整合包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.6</version> </dependency> <!-- 连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.9</version> </dependency> <!-- Junit测试 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> <!-- MySQSL驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.28</version> </dependency> <!-- log4j日志 --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- Pagehelper分页 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.3.0</version> </dependency> <!-- 日志 --> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.11</version> </dependency> <!-- ServletAPI --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.2.2</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> <!-- Spring和Thymeleaf整合包 --> <dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring5</artifactId> <version>3.0.14.RELEASE</version> </dependency> </dependencies> </project>
③ 创建表
CREATE TABLE `t_emp` ( `emp_id` int(11) NOT NULL AUTO_INCREMENT, `emp_name` varchar(20) DEFAULT NULL, `age` int(11) DEFAULT NULL, `sex` char(1) DEFAULT NULL, `email` varchar(50) DEFAULT NULL, PRIMARY KEY (`emp_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2.2、配置web.xml
<!-- 配置Spring的编码过滤器 --> <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>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 配置处理请求方式的过滤器 --> <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> <!-- 配置SpringMVC的前端控制器 --> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 设置SpringMVC配置文件自定义位置和名称 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 将DispatcherServlet的初始化时间提前到服务器启动时 --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 配置Spring的监听器,在服务器启动时加载Spring的配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 设置Spring配置文件自定义的位置和名称 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring.xml</param-value> </context-param>
2.3、配置SpringMVC的配置文件
<!-- 扫描控制层组件 --> <context:component-scan base-package="com.jingchao.ssm.controller"/> <!--配置视图解析器--> <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> <!-- 配置默认的servlet处理静态资源 --> <mvc:default-servlet-handler/> <!-- 开启mvc的注解驱动 --> <mvc:annotation-driven/> <!-- 配置视图控制器 --> <mvc:view-controller path="/" view-name="index"/> <!-- 配置文件上传解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>
2.4、搭建MyBatis环境
① 创建属性文件jdbc.properties
jdbc.driver=com.mysql.cj.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC jdbc.username=root jdbc.password=123456
② 创建MyBatis核心配置文件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> <settings> <!-- 将下划线映射为驼峰 --> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <plugins> <!-- 配置分页插件 --> <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin> </plugins> </configuration>
③ 创建Mapper接口和映射文件
public interface EmployeeMapper { }
<?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="com.jingchao.ssm.mapper.EmployeeMapper"> </mapper>
④ 创建日志文件log4j.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender"> <param name="Encoding" value="UTF-8" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS}%m (%F:%L) \n" /> </layout> </appender> <logger name="java.sql"> <level value="debug" /> </logger> <logger name="org.apache.ibatis"> <level value="info" /> </logger> <root> <level value="debug" /> <appender-ref ref="STDOUT" /> </root> </log4j:configuration>
2.5、配置Spring的配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 扫描组件(除控制层) --> <context:component-scan base-package="com.jingchao.ssm"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 引入jdbc.properties --> <context:property-placeholder location="classpath:jdbc.properties"/> <!-- 配置数据源 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 开启事务的注解驱动 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- 配置SqlSessionFactoryBean,可以直接在Spring的IOC中获取SqlSessionFactory --> <bean class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 设置MyBatis核心配置文件的路径 --> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!-- 设置数据源 --> <property name="dataSource" ref="dataSource"/> <!-- 设置类型别名所对应的包 --> <property name="typeAliasesPackage" value="com.jingchao.ssm.pojo"/> <!-- 设置映射文件的位置,只有当映射文件和接口的包名不一致的情况才设置 --> <!-- <property name="mapperLocations" value="classpath:mapper/*.xml"/> --> <!-- 配置插件 --> <!-- <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"/> </array> </property> --> </bean> <!-- 配置mapper接口的扫描,可以将指定包下面的所有mapper接口通过SqlSession创建代理实现类对象,并将这些对象交给IOC容器管理 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.jingchao.ssm.mapper"/> </bean> </beans>
2.6、测试功能
实体类Employee
package com.jingchao.ssm.pojo; public class Employee { private Integer empId; private String empName; private Integer age; private String gender; private String email; public Employee() { } public Employee(Integer empId, String empName, Integer age, String gender, String email) { this.empId = empId; this.empName = empName; this.age = age; this.gender = gender; this.email = email; } public Integer getEmpId() { return empId; } public void setEmpId(Integer empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "Employee{" + "empId=" + empId + ", empName='" + empName + '\'' + ", age=" + age + ", gender='" + gender + '\'' + ", email='" + email + '\'' + '}'; } }
创建控制层组件EmployeeController
@Controller public class EmployeeController { }
创建接口EmployeeService
public interface EmployeeService { }
创建实现类EmployeeServiceImpl
@Service @Transactional public class EmployeeServiceImpl implements EmployeeService { }
2.6.1、员工列表
① 控制层
@Controller public class EmployeeController { @Autowired private EmployeeService employeeService; @GetMapping("/employee") public String getAllEmployee(Model model){ List<Employee> list = employeeService.getAllEmployee(); model.addAttribute("list",list); return "employee_list"; } }
② Service接口
public interface EmployeeService { /** * 查询所有员工信息 * @return */ List<Employee> getAllEmployee(); }
③ Service实现类
@Service @Transactional public class EmployeeServiceImpl implements EmployeeService { @Autowired private EmployeeMapper employeeMapper; @Override public List<Employee> getAllEmployee() { return employeeMapper.getAllEmployee(); } }
④ Mapper接口
public interface EmployeeMapper { /** * 查询所有员工信息 * @return */ List<Employee> getAllEmployee(); }
⑤ Mapper映射文件
<mapper namespace="com.jingchao.ssm.mapper.EmployeeMapper"> <!-- List<Employee> getAllEmployee(); --> <select id="getAllEmployee" resultType="Employee"> select * from t_emp </select> </mapper>
⑥ 创建employee_list页面
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>员工列表</title> <link rel="stylesheet" th:href="@{/static/css/index_work.css}"> </head> <body> <table> <tr> <th colspan="6">员工列表</th> </tr> <tr> <th>流水号</th> <th>员工姓名</th> <th>年龄</th> <th>性别</th> <th>邮箱</th> <th>操作</th> </tr> <tr th:each="employee,status : ${list}"> <td th:text="${status.count}"></td> <td th:text="${employee.empName}"></td> <td th:text="${employee.age}"></td> <td th:text="${employee.gender}"></td> <td th:text="${employee.email}"></td> <td> <a href="">删除</a> <a href="">修改</a> </td> </tr> </table> </body> </html>
在index页面提供超链接
<a th:href="@{/employee}">查询所有员工信息</a>
2.6.2、分页功能
在员工列表的基础上实现分页功能
① 控制层
@GetMapping("/employee/page/{pageNum}") public String getEmployeePage(@PathVariable("pageNum") Integer pageNum, Model model){ // 获取员工的分页信息 PageInfo<Employee> page = employeeService.getEmployeePage(pageNum); // 将分页数据共享到请求域中 model.addAttribute("page",page); return "employee_list_page"; }
② Service接口
/** * 获取员工的分页信息 * @return */ PageInfo<Employee> getEmployeePage(Integer pageNum);
③ Service实现类
@Override public PageInfo<Employee> getEmployeePage(Integer pageNum) { // 开启分页功能 PageHelper.startPage(pageNum,5); // 查询所有员工信息 List<Employee> list = employeeMapper.getAllEmployee(); // 获取分页相关数据 PageInfo<Employee> pageInfo = new PageInfo<>(list, 5); return pageInfo; }
④ 创建employee_list_old页面
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>员工分页列表</title> <link rel="stylesheet" th:href="@{/static/css/index_work.css}"> </head> <body> <table> <tr> <th colspan="6">员工列表</th> </tr> <tr> <th>流水号</th> <th>员工姓名</th> <th>年龄</th> <th>性别</th> <th>邮箱</th> <th>操作</th> </tr> <tr th:each="employee,status : ${page.list}"> <td th:text="${status.count}"></td> <td th:text="${employee.empName}"></td> <td th:text="${employee.age}"></td> <td th:text="${employee.gender}"></td> <td th:text="${employee.email}"></td> <td> <a href="">删除</a> <a href="">修改</a> </td> </tr> </table> <div style="text-align: center;"> <a th:if="${page.hasPreviousPage}" th:href="@{/employee/page/1}">首页</a> <a th:if="${page.hasPreviousPage}" th:href="@{'/employee/page/'+${page.prePage}}">上一页</a> <span th:each="num : ${page.navigatepageNums}"> <a th:if="${page.pageNum == num}" style="color: red" th:href="@{'/employee/page/'+${num}}" th:text="'['+${num}+']'"></a> <a th:if="${page.pageNum != num}" th:href="@{'/employee/page/'+${num}}" th:text="${num}"></a> </span> <a th:if="${page.hasNextPage}" th:href="@{'/employee/page/'+${page.nextPage}}">下一页</a> <a th:if="${page.hasNextPage}" th:href="@{'/employee/page/'+${page.pages}}">末页</a> </div> </body> </html>
⑤ 效果预览