整合Spring & Spring MVC & MyBatis
1.建工程
创建一个Maven工程ssm,分别在pom.xml文件中导入Spring、Spring MVC以及MyBatis的相关依赖
代码语言:javascript复制<properties>
<spring-version>5.3.13</spring-version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--spring jdbc依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring-version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.14</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
</dependencies>
添加Web Application,勾选创建web.xml
2.写配置
2.1 web.xml的配置
对一个Web应用来说,首先要配置web.xml,其中配置了Spring配置文件的路径、Spring MVC前端控制器配置文件的路径以及解决乱码和Rest请求的过滤器
代码语言:javascript复制<?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">
<!--Spring-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.xml</param-value>
</context-param>
<!--缺少监听器的话在Tomcat启动时会报错创建Bean失败-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--DispatchServlet-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<!--"/" 代表拦截所有请求,/*拦截所有请求包括jsp页面这些请求-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--解决POST请求中文乱码问题-->
<filter>
<filter-name>characterFilter</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>
</filter>
<filter-mapping>
<filter-name>characterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!--Rest支持-->
<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>
</web-app>
2.2 Spring MVC的配置
在WEB-INF目录下新建dispatcherServlet-servlet.xml,这个位置是Spring MVC会默认查找的路径,文件名也是Spring MVC默认的查找名即配置的DispatcherServlet名称-serverlt.xml,所以在web.xml中的servlet-class标签下并没有配置Spring MVC配置文件的路径,使用的是默认的路径和默认的名称。在dispatcherServlet-servlert.xml中先后配置扫描cotroller包、视图解析器、静态资源和动态资源扫描的配置
代码语言:javascript复制<?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:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.3.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/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.citi" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--配置试图解析器,自动拼接页面地址,自动在jsp页面前增加/WEB-INF/pages/-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 默认前端控制器是拦截所有资源(除过jsp),js文件就404了;要js文件的请求是交给tomcat处理的
http://localhost:8080/7.SpringMVC_crud/scripts/jquery-1.9.1.min.js -->
<!-- 告诉SpringMVC,自己映射的请求就自己处理,不能处理的请求直接交给tomcat -->
<!-- 静态资源能访问,动态映射的请求就不行 -->
<mvc:default-servlet-handler/>
<!-- springmvc可以保证动态请求和静态请求都能访问 -->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
2.3 Spring 的配置
在resources目录下新建application.xml作为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:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.3.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
<!--扫描除了控制器之前的其他包-->
<context:component-scan base-package="com.citi">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--引用外部配置文件-->
<context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
<!--数据库连接池配置-->
<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}"/>
<property name="initialSize" value="${jdbc_initialSize}"/>
<property name="maxActive" value="${jdbc_maxActive}"/>
</bean>
<!--事务管理器配置-->
<bean id="dataSourceTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--开启基于注解的配置模式-->
<tx:annotation-driven transaction-manager="dataSourceTransactionManager" />
</beans>
db.properties配置了数据库连接的相关信息
代码语言:javascript复制jdbc_driver=com.mysql.cj.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai
jdbc_username=root
jdbc_password=root
jdbc_initialSize=10
jdbc_maxActive=20
2.4 MyBatis的配置
配置MyBatis全局配置文件mybatis-config.xml,只配置settings标签就可以,数据源、mapper等配置在Spring配置文件application.xml中设置。
代码语言:javascript复制<?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"/>
<!--开启懒加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
<!--开启二级缓存-->
<setting name="cacheEnabled" value="true"/>
</settings>
</configuration>
在Spring配置文件application.xml中将Myabtis整合到Spring中,需要先导入Mybatis-Spring的依赖
代码语言:javascript复制<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.7</version>
</dependency>
在application.xml中增加SqlSessionFactoryBean配置
代码语言:javascript复制<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="mybatis-config.xml"></property>
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:/mappers/*.xml"></property>
</bean>
将mapper包下的Mapper接口全部加入到Spring容器中
代码语言:javascript复制<!--持久层接口加入到Spring容器-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--指定接口所在的包-->
<property name="basePackage" value="com.citi.mapper"></property>
</bean>
2.5 其他配置
mybatis日志配置logback.xml,放在resource目录下。可以在控制台打印出SQL
代码语言:javascript复制<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%thread] %d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="console"/>
</root>
</configuration>
至此Spring、Spring MVC、MyBatis三个框架整合完成
3.测试
持久层Mapper接口测试
数据库表与上一篇QA 由浅入深持久层框架(七)- MyBatis Cache用到的是同一张表,即t_teacher,这里不再重复
新建entity包,增加Teacher实体类
代码语言:javascript复制@Data
public class Teacher implements Serializable {
private Integer id;
private String teacherName;
private String className;
private String address;
private Date birthDate;
}
新建mapper包,增加TeacherMapper接口,并增加一个根据id查询Teahcer的方法
代码语言:javascript复制public interface TeacherMapper {
Teacher getTeacherById(Integer id);
}
在resources目录下新增mappers文件夹,用来存放Mapper接口的SQL映射文件,新建TeacherMapper接口的SQL映射文件TeacherMapper.xml
代码语言:javascript复制<?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.citi.mapper.TeacherMapper">
<!--开启二级缓存-->
<cache></cache>
<select id="getTeacherById" resultType="com.citi.entity.Teacher">
select * from t_teacher where id = #{id}
</select>
</mapper>
在test包下新增TeacherMapper接口的测试类TeacherMapperTest,新增getTeacherById方法的测试方法
代码语言:javascript复制@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:application.xml")
public class TeacherMapperTest {
@Autowired
private TeacherMapper teacherMapper;
@Test
public void getTeacherById() {
teacherMapper.getTeacherById(1);
}
}
测试类中用到了Spring Test,主要不要忘记类上的两个注解
执行测试方法
成功查询到了id为2的Teacher对象
Service层测试
新建service包,在该包下新增TeacherService接口,新增一个根据id查找Teacher的方法
代码语言:javascript复制public interface TeacherService {
Teacher findTeacherById(Integer id);
}
在service包下新增impl包,用来保存接口的实现类,在impl包中新增TeacherService接口的实现类TeacherServiceImpl
代码语言:javascript复制@Service
public class TeacherServiceImpl implements TeacherService {
@Autowired
private TeacherMapper teacherMapper;
@Override
public Teacher findTeacherById(Integer id) {
return teacherMapper.getTeacherById(id);
}
}
增加TeacherService的测试类TeacherServiceTest
代码语言:javascript复制@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:application.xml")
public class TeacherServiceTest {
@Autowired
private TeacherService teacherService;
@Test
public void findTeacherById() {
Teacher teacher = teacherService.findTeacherById(1);
System.out.println(teacher);
}
}
执行测试
控制台成功输出id为1的Teacher对象,说明service层调用mapper层成功
Controller层测试
配置Tomcat前,首先选中项目,点击IDEA菜单的File选项,点击Project Structure,左边选择Artifacts,在WEB-INF下新建一个lib目录,将右侧的jar包全部选中并导入lib文件夹中
配置Tomcat,点击IDEA的DEIT Configurations,配置一个本地的Tomcat
并将项目部署到Tomcat中
编写Controller层代码,新建controller包,增加TeacherController类
代码语言:javascript复制@Controller
@RequestMapping("/teacher")
public class TeacherController {
@Resource
public TeacherService teacherService;
@RequestMapping("/{id}")
public ModelAndView findTeacher(@PathVariable("id") Integer id){
Teacher teacher = teacherService.findTeacherById(id);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("teacher",teacher);
modelAndView.setViewName("success");
return modelAndView;
}
}
视图解析器已经配置了WEB-INF下的pages目录,所以在WEB-INF下新增pages目录并新增一个jsp文件success.jsp
代码语言:javascript复制<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h2>SUCCESS</h2>
<h3>${teacher}</h3>
</body>
</html>
启动Tomcat,浏览器输入地址http://localhost:8080/teacher/1, 查询id为1的Teacher的信息
Spring、Spring MVC、MyBatis整合成功!