spring和springmvc可以使用同一个配置文件,但是建议分开。所谓整合就是把spring和springmvc分开各自管理自己的内容。
1、创建maven工程
2、导入依赖
3、配置web.xml
4、搭建SpringMVC框架
5、配置Spring的配置文件(扫描组件、引入jdbc.properties、配置数据源)
6、搭建MyBatis框架
7、Spring整合MyBatis
一、编写web.xml
虽然老师是一行一行敲出来的,但是这东西能看得懂会改就行,建议直接复制。
前置知识1:
在服务器启动时获取springmvc ioc容器,自动装配就必须完成,
那么怎么保证Contoller中的service能装配成功呢?即怎么让spring容器的获取一定要早于springmvc容器获取
过滤器和监听器都可以,但是建议用监听器。我们想到ServletContextListener它的初始化是最早执行的,服务器启动时执行。
监听器相关知识传送点:
22-05-31 西安 javaweb(12) 监听器listener和过滤器filter、编码过滤器、登录过滤器、事务过滤器_£小羽毛的博客-CSDN博客
spring当然也想到了,就给我提供了这样一个监听器ContextLoaderListener
方法内容:
@Override
public void contextInitialized(ServletContextEvent event) {
initWebApplicationContext(event.getServletContext());
}
创建了spring 的ioc容器,并把spring的ioc容器创建之后也会共享到应用域
前置知识2:
spring的配置文件默认的位置 WEB-INF下,默认名称 applicationContext.xml
<context-param>自定义spring的配置文件位置和名称
servlet相关知识传送点:
前置知识3:
SpringMVC的IOC容器和Spring的IOC容器的关系?
Spring的IOC容器是SpringMVC的IOC容器的父容器,子容器可以访问父容器中的bean,但是反之不行
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置编码过滤器-->
<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>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--设置SpringMVC配置文件自定义的位置和名称-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.xml</param-value>
</init-param>
<!--将DispatcherServlet的初始化时间提前到服务器启动时-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--配置Spring的监听器,在服务器启动时加载Spring的配置文件,获取IOC容器-->
<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>
</web-app>
二、编写springmvc的配置文件spring-mvc.xml
这个文件的位置和名称在web.xml中都是可以自定义设置的。我这里并没有配置拦截器和异常处理器,甚至多配置了一个文件上传解析器。
SpringMVC中配置的内容:
扫描控制层组件、视图解析器、默认的servlet、mvc的注解驱动、视图控制器
文件上传解析器、拦截器、异常解析器
spring-mvc.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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描控制层组件-->
<context:component-scan base-package="com.atguigu.ssm.controller"></context:component-scan>
<!--配置视图解析器-->
<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"></mvc:view-controller>
<!--配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
</beans>
三、编写spring.xml
Spring中配置的内容:
扫描除控制层以外的组件、引入properties文件、配置数据源、aop相关配置、配置事务管理器、开启事务的注解驱动、事务通知、整合MyBatis相关内容
前置知识1:
spring如何整合mybatis,就2个标签
SqlSessionFactoryBean:配置用于创建SqlSessionFactory的工厂bean,就可以通过ioc容器直接获取SqlSessionFactory对象。MapperScannerConfigurer:将所指定包下的mapper接口,通过SqlSession.getMapper()创建其代理实现类对象,并将这些对象交给IOC容器管理(可以对mapper接口进行自动装配)
<bean class="org.mybatis.spring.SqlSessionFactoryBean"> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> </bean>
前置知识2:
SqlSessionFactoryBean标签中的mapperLocations属性可以不配置,什么时候需要必须配置呢?
若mapper接口和映射文件所在的包不一致,则必须设置该标签
<property name="mapperLocations" value="classpath:mapper/*.xml"></property> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.atguigu.ssm.mapper"></property> </bean>
spring.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: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.atguigu.ssm">
<!--排除对控制层组件的扫描-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--引入jdbc.properties-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--配置数据源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--配置事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--
开启事务的注解驱动
将使用@Transactional注解标识的方法或类中所有的方法被事务进行管理
-->
<tx:annotation-driven transaction-manager="transactionManager" />
<!--配置SqlSessionFactoryBean-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<!--设置数据源-->
<property name="dataSource" ref="dataSource"></property>
<!--设置MyBatis的核心配置文件(可以不设置)-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
<!--设置类型别名所在的包-->
<property name="typeAliasesPackage" value="com.atguigu.ssm.pojo"></property>
<!--
引入映射文件
当配置了MapperScannerConfigurer时,若mapper接口和映射文件所在的包一致,则该标签可以省略不写
但是若mapper接口和映射文件所在的包不一致,则必须设置该标签
-->
<!--
<property name="mapperLocations" value="classpath:mapper/*.xml"></property>
-->
</bean>
<!--
配置mapper接口的扫描
将所指定包下的mapper接口,通过SqlSession.getMapper()创建其代理实现类对象
并将这些对象交给IOC容器管理
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.atguigu.ssm.mapper"></property>
</bean>
</beans>
settings 和plugins 写在spring的配置文件会看着麻烦,不如就写在配置在核心配置文件
mybatis-config.xml中呢
四、编写 mybtis-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>
jdbc.properties文件:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC
jdbc.username=root
jdbc.password=123456
五、测试SSM,实现分页功能
一定要在pom.xml中加pagehelper的依赖,在mybatis-config.xml中加PageInterceptor插件
分页插件是拦截器,我们直接查询所有,该插件自动帮我们加limit关键字
@Override
public PageInfo<Employee> getEmployeePage(Integer pageNo) {
//开启分页功能
PageHelper.startPage(pageNo,4);
//查询员工信息
List<Employee> list = employeeMapper.getAllEmployee();
//获取分页相关信息的对象
PageInfo<Employee> pageInfo = new PageInfo<>(list, 5);
return pageInfo;
}
这块是后来补上的:
分页查询,用Page来接收,是因为
public class Page<E> extends ArrayList<E>public PageInfo<UserFollowVo> findListPage(int pageNum, int pageSize, Long userId) { PageHelper.startPage(pageNum,pageSize); Page<UserFollowVo> listPage = userFollowMapper.findListPage(userId); return new PageInfo<>(listPage,10); }
注意在EmployeeMapper接口上可没有什么@Repository,不要急病乱投医
public interface EmployeeMapper {
/**
* 获取所有的员工信息
* @return
*/
List<Employee> getAllEmployee();
}
老师说:分页功能,难在页面中跟分页相关的超链接。还好我们有pageInfo,不然真的很难
employee_list.html:
<!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>
<tr>
<td colspan="6">
<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}" th:href="@{'/employee/page/'+${num}}" th:text="'【'+${num}+'】'" style="color: red;"></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>
总<span th:text="${page.total}"></span>条数据,当前<span th:text="${page.pageNum}"></span>/<span th:text="${page.pages}"></span>
</td>
</tr>
</table>
</body>
</html>
在浏览器的控制台输出pageInfo对象,也就是我们上面共享在请求域中的page, 它就长这个样子!
点开list,就可以看到我们要循环遍历显示的员工信息了
最终页面效果如下,经我测试,红色框里关于分页的所有功能都是好用的!高级上档次啊