文章目录
- 1.ssm整合过程
- 1.1步骤
- 1.2 Spring整合SpringMVC的问题
- 2.准备工作
- 2.1 添加依赖
- 2.2 创建数据库
- 3.相关配置
- 3.1 整合Spring和Mybatis
- 3.2 引入SpringMVC
- 3.3 spring整合入web项目
- 4.测试整合效果
1.ssm整合过程
1.1步骤
(1)Spring整合MyBatis
通过service层,dao层都注入到Spring容器。
(2)引入配置SpringMVC
把Controller层注入到SpringMVC容器。
(3)让web项目启动时自动读取spring配置文件来创建spring容器
可以使用ContextLoadListener来实现Spring容器的创建
1.2 Spring整合SpringMVC的问题
(1)为什么需要Spring, SpringMVC两个容器?
因为Controller层放在SpringMVC容器中才能发挥其作用(才能处理请求),Service层放在Spring容器才能发挥其作用(才能使用声明式事务)。
(2)SpringMVC容器的Controller如何获取Spring容器的Service对象?
Spring容器相当于父容器,而SpringMVC相当于子容器,子容器除了能使用自己容器中的对象,还可以使用父容器中的对象。
(3)如何让两个容器发生父子关系?
通过ContextLoaderListener。
(a)当服务器启动后,会创建ServletContext
(b)ContextLoaderListener在监听创建ServletContext后,会经过读取配置文件位置,找到配置文件位置,初始化IOC等操作创建IOC容器。
(c)将IOC容器放进ServletContext中
(d)Dispatcher启动时,创建完SpringMVC容器后,会从ServletContext中获取Spring容器对象,并设置其为父对象,这样子容器就能获取到父容器中的bean。
2.准备工作
2.1 添加依赖
<!--Spring-context-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--AOP相关依赖-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- mybatis整合到Spring的整合包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.4</version>
</dependency>
<!--mybatis依赖-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.4</version>
</dependency>
<!--log4j依赖,打印mybatis日志-->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--分页查询,pagehelper-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.0.0</version>
</dependency>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!-- druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- spring整合junit的依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
<scope>provided</scope>
</dependency>
<!-- servlet依赖 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--jsp依赖 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<!--springmvc的依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!-- jackson,帮助进行json转换-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<!--commons文件上传,如果需要文件上传功能,需要添加本依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
2.2 创建数据库
CREATE DATABASE /*!32312 IF NOT EXISTS*/`mybatis_db` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `mybatis_db`;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
insert into `user`(`id`,`username`,`age`,`address`) values (1,'UZI',19,'上海'),(2,'PDD',25,'上海');
3.相关配置
3.1 整合Spring和Mybatis
spring的核心配置文件:
【applicationContext.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"
xmlns:aop="http://www.springframework.org/schema/aop"
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 http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!--组件扫描,排除controller,其他的放入spring-->
<context:component-scan base-package="com.sdnu">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
</context:component-scan>
<!--读取properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!--创建连接池注入容器-->
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource">
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClassName" value="${jdbc.driver}"></property>
</bean>
<!--spring整合mybatis后控制的创建获取SqlSessionFactory的对象-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactory">
<!--配置连接池-->
<property name="dataSource" ref="dataSource"></property>
<!--配置mybatis配置文件的路径-->
<property name="configLocation" value="classpath:mybatis-config.xml"></property>
</bean>
<!--mapper扫描配置,扫描到的mapper对象会被注入Spring容器中-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" id="mapperScannerConfigurer">
<property name="basePackage" value="com.sdnu.dao"></property>
</bean>
<!--开启aop注解支持-->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<!--声明式事务相关配置-->
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
</beans>
【jdbc.properties】
jdbc.url=jdbc:mysql://localhost:3306/mybatis_db?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
jdbc.driver=com.mysql.jdbc.Driver
jdbc.username=root
jdbc.password=root
【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>
<!--指定使用log4j打印Mybatis日志-->
<setting name="logImpl" value="LOG4J"/>
</settings>
<!--配置别名包,放实体类,类名叫User,写mapper配置时应该写全类名,但配置完这个后,就只用写User了-->
<typeAliases>
<package name="com.sdnu.domain"></package>
</typeAliases>
<plugins>
<!-- 注意:分页助手的插件,配置在通用mapper之前 -->
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 指定方言 -->
<property name="dialect" value="mysql"/>
</plugin>
</plugins>
</configuration>
【log4j.properties】
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout
3.2 引入SpringMVC
【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">
<!--
SpringMVC只扫描controller包即可
-->
<context:component-scan base-package="com.sdnu.controller"/>
<!-- 解决静态资源访问问题,如果不加mvc:annotation-driven会导致无法访问handler-->
<mvc:default-servlet-handler/>
<!--解决响应乱码-->
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="utf-8"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--配置视图解析器 前后端不分离项目使用-->
<!-- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="viewResolver">
<!–要求拼接的前缀–>
<property name="prefix" value="/WEB-INF/page/"></property>
<!–要拼接的后缀–>
<property name="suffix" value=".jsp"></property>
</bean>-->
<!--配置拦截器-->
<!-- <mvc:interceptors>
<mvc:interceptor>
<!–
–>
<mvc:mapping path="/**"/>
<!–配置排除拦截的路径–>
<mvc:exclude-mapping path="/"/>
<!–配置拦截器对象注入容器–>
<bean class=""></bean>
</mvc:interceptor>
</mvc:interceptors>-->
<!--
文件上传解析器
注意:id 必须为 multipartResolver
如果需要上传文件时可以放开相应配置
-->
<!--<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">-->
<!--<!– 设置默认字符编码 –>-->
<!--<property name="defaultEncoding" value="utf-8"/>-->
<!--<!– 一次请求上传的文件的总大小的最大值,单位是字节–>-->
<!--<property name="maxUploadSize" value="#{1024*1024*100}"/>-->
<!--<!– 每个上传文件大小的最大值,单位是字节–>-->
<!--<property name="maxUploadSizePerFile" value="#{1024*1024*50}"/>-->
<!--</bean>-->
</beans>
修改【web.xml】
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--
为DispatcherServlet提供初始化参数的
设置springmvc配置文件的路径
name是固定的,必须是contextConfigLocation
value指的是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>DispatcherServlet</servlet-name>
<!--
/ 表示当前servlet映射除jsp之外的所有请求(包含静态资源)
*.do 表示.do结尾的请求路径才能被SpringMVC处理(老项目会出现)
/* 表示当前servlet映射所有请求(包含静态资源,jsp),不应该使用其配置DispatcherServlet
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--乱码处理过滤器,由SpringMVC提供-->
<!-- 处理post请求乱码 -->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<!-- name固定不变,value值根据需要设置 -->
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<!-- 所有请求都设置utf-8的编码 -->
<url-pattern>/*</url-pattern>
</filter-mapping>
3.3 spring整合入web项目
【web.xml】
<!--配置spring的配置文件路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--配置监听器,可以再应用被部署的时候创建spring容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
4.测试整合效果
[UserController.java]
package com.sdnu.controller;
import com.sdnu.domain.User;
import com.sdnu.service.UserService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@RestController
public class UserController {
@Autowired
UserService userService;
@GetMapping("/user/{id}")
public User findById(@PathVariable("id") Integer id){
User user = userService.findById(id);
return user;
}
}
[UserDao.java]
package com.sdnu.dao;
import com.sdnu.domain.User;
public interface UserDao {
User findById(Integer id);
}
[User.java]
package com.sdnu.domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Integer id;
private String username;
private Integer age;
private String address;
}
[UserServiceImpl.java]
package com.sdnu.service.Impl;
import com.sdnu.dao.UserDao;
import com.sdnu.domain.User;
import com.sdnu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public User findById(Integer id) {
return userDao.findById(id);
}
}
[UserService.java]
package com.sdnu.service;
import com.sdnu.domain.User;
public interface UserService {
User findById(Integer id);
}
[UserDao.xml]
<?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.sdnu.dao.UserDao">
<select id="findById" resultType="com.sdnu.domain.User">
select * from user where id = #{id}
</select>
</mapper>
加入tomcat插件
[pom.xml]
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>80</port>
<path>/</path>
<uriEncoding>utf-8</uriEncoding>
</configuration>
</plugin>
</plugins>
</build>
运行: