SSM整合
搭建整合环境
思路
- 整合说明:SSM整合可以使用多种方式,咱们会选择XML + 注解的方式
- 先搭建整合的环境
- 先把Spring的配置搭建完成(spring整合其他两个)
- 再使用Spring整合SpringMVC框架
- 最后使用Spring整合MyBatis框架
步骤
导入坐标依赖
<properties> <spring.version>5.0.2.RELEASE</spring.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mysql.version>5.1.6</mysql.version> <mybatis.version>3.4.5</mybatis.version> </properties> <dependencies> <!-- spring --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</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-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-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>compile</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- log start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies>
编写实体类,在ssm_domain项目中编写
编写dao接口
编写service接口和实现类
Spring框架代码的编写
步骤
创建applicationContext.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: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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!-- 开启注解扫描,要扫描的是service和dao层的注解,要忽略web层注解,因为web层让SpringMVC框架 去管理 --> <context:component-scan base-package="cn.itcast"> <!-- 配置要忽略的注解(spring配置文件只扫描service和dao的注解,表现层controller的注解不扫) --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> </beans>
Spring整合SpringMVC框架
springmvc只加载了controller的bean,spring的applicationContext.xml文件并没有加载,service也没有加到spring容器中,controller注入service不成功。所以整合目的是在服务器启动时,也会加载spring的配置文件,service就可以被controller注入成功并调用了。
那么如何在服务器启动时加载呢,服务器启动有一个servletcontext域对象会被创建,关闭时销毁。在spring-web的依赖中有一个监听器ContextLoaderListener来监听servletContext的创建和销毁。
这个监听器默认是监听
步骤
在web.xml中配置DispatcherServlet前端控制器
<!-- 配置前端控制器:服务器启动时加载,需要加载springmvc.xml配置文件 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 配置初始化参数,创建完DispatcherServlet对象,加载springmvc.xml配置文件 --> <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>
在web.xml中配置DispatcherServlet过滤器解决中文乱码
<!-- 配置解决中文乱码的过滤器 --> <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> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
创建springmvc.xml的配置文件
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 扫描controller的注解,别的不扫描,需要用exclude --> <context:component-scan base-package="cn.itcast"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 配置视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- JSP文件所在的目录 --> <property name="prefix" value="/WEB-INF/pages/" /> <!-- 文件的后缀名 --> <property name="suffix" value=".jsp" /> </bean> <!-- 设置静态资源不过滤 --> <mvc:resources location="/css/" mapping="/css/**" /> <mvc:resources location="/images/" mapping="/images/**" /> <mvc:resources location="/js/" mapping="/js/**" /> <!-- 开启对SpringMVC注解的支持 --> <mvc:annotation-driven /> <!--纯注解的方式:@EnableWebMvc--> </beans>
- 测试SpringMVC的框架搭建是否成功
编写index.jsp和list.jsp编写,超链接 <a href="account/findAll">查询所有</a>
创建AccountController类,编写方法,进行测试 @Controller @RequestMapping("/account") public class AccountController { /** * 查询所有的数据 */ @RequestMapping("/findAll") public String findAll() { System.out.println("表现层:查询所有账户..."); return "list"; } }
- 整合
- 目的:在controller中能成功的调用service对象中的方法
- 在项目启动的时候,就去加载applicationContext.xml(spring的)的配置文件
在web.xml中配置 ContextLoaderListener监听器
<!-- 配置Spring的监听器,spring-web提供的监听器 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listenerclass> </listener> <!-- 配置加载类路径的配置文件 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
在controller中注入service对象,调用service对象的方法进行测试
@Controller @RequestMapping("/account") public class AccountController { @Autowired private AccountService accoutService; /** * 查询所有的数据 */ @RequestMapping("/findAll") public String findAll() { System.out.println("表现层:查询所有账户..."); accoutService.findAll(); return "list"; } }
Spring整合SpringMVC框架(纯注解版)
- 创建applicationContext.xml的(spring的)配置文件,注解中叫配置类
//Spring的容器不扫描controller
@ComponentScan(value="com.atguigu",excludeFilters={
@Filter(type=FilterType.ANNOTATION,classes={Controller.class})
}
public class RootConfig{
}
- 创建SpringMVC.xml的配置文件,注解中叫配置类
//SpringMVC容器只扫描controller
//只扫描需要禁用默认的过滤规则 useDefaultFilters=false
@ComponentScan(value="com.atguigu",includeFilters={
@Filter(type=FilterType.ANNOTATION,classes={Controller.class},useDefaultFilters=false)
}
public class AppConfig{
}
- 创建MyWebAppInitializer,继承AbstractAnnotationConfigDispatcherServletInitializer
//Web容器启动的时候创建对象,调用方法来初始化以前前端控制器
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
//重写方法
//获取根容器的配置类,spring配置类
protected Class<?>[] getRootConfigClasses(){
return new Class<?>[]{RootConfig.class};
}
//获取web容器的配置类,springMVC配置类
protected Class<?>[] getServletConfigClasses(){
return new Class<?>[]{AppConfig.class};
}
//获取DispatcherServlet的映射信息
// /:拦截所有请求(包括静态资源js,css),但是不包括*.jsp
// /*:拦截所有请求,jsp也会拦截
protected String[] getServletMappings(){
return new String[]{"/"};
}
}
- 定制mvc:开启注解,配置视图解析器……
三大步:
@EnableWebMvc,开启SpringMVC定制功能,与<mvc:annotation-driven />功能相同
继承WebMvcConfigurerAdapter
重写方法,进行定制
@ComponentScan(value="com.atguigu",includeFilters={
@Filter(type=FilterType.ANNOTATION,classes={Controller.class},useDefaultFilters=false)
}
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter{
//重写方法 alt+/
//配置视图解析器
public void configureViewResolvers(ViewResolverRegistry registry){
//前缀,后缀
registry.jsp("/WEB-INF/views/",".jsp");
}
//配置静态资源访问,所有静态资源交给tomcat来访问,不使用springMVC进行过滤
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer){
configurer.enable();
}
//配置拦截器
public void addInterceptors(InterceptorRegistry registry){
//将自定义的拦截器类加到组件中,并设置拦截的路径
registry.addInterceptor(new MyFirstInterceptor()).addPathPatterns("/**");
}
}
Spring整合MyBatis框架
步骤:
在web项目中编写SqlMapConfig.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> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql:///ssm"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <!-- 使用的是注解 --> <mappers> <!-- <mapper class="cn.itcast.dao.AccountDao"/> --> <!-- 该包下所有的dao接口都可以使用 --> <package name="cn.itcast.dao"/> </mappers> </configuration>
在AccountDao接口的方法上添加注解,编写SQL语句
public interface AccountDao { @Insert(value="insert into account (name,money) values (#{name},#{money})") public void saveAccount(Account account); @Select("select * from account") public List<Account> findAll(); }
编写测试的方法
@Test public void run1() throws Exception { // 加载配置文件 InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml"); // 创建工厂 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(inputStream); // 创建sqlSession对象 SqlSession session = factory.openSession(); // 获取代理对象 AccountDao dao = session.getMapper(AccountDao.class); // 调用查询的方法 List<Account> list = dao.findAll(); for (Account account : list) { System.out.println(account); } // 释放资源 session.close(); inputStream.close(); }
整合
- 目的:将生成的代理对象存入到Spring的容器当中(之前是通过自己的核心配置文件来配置)
SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml(spring的)配置文件中
<!-- 配置C3P0的连接池对象 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql:///ssm" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!-- 配置SqlSession的工厂,底层工厂创建sqlsession,sqlsession创建代理对象存入ioc容器中--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!--如果不是纯注解方式,还需要注入mybatis核心配置文件--> <property name="configLocation" value="classpath:sqlMapConfig.xml"></property> </bean> <!-- 配置扫描dao的包,底层告诉sqlsession创建谁的代理对象 --> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--注入sqlSessionFactory--> <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> --> <property name="basePackage" value="cn.itcast.dao"/> </bean>
在AccountDao接口中添加@Repository注解
在service中注入dao对象,测试(这样真正注入的对象就是代理对象了,而不是原来daoImpl的实现类对象)
配置Spring的声明式事务管理
<!-- 配置事务管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事务的通知 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" read-only="true"/> <tx:method name="*" isolation="DEFAULT"/> </tx:attributes> </tx:advice> <!-- 配置 aop --> <aop:config> <!-- 配置切入点表达式 --> <aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt1"/> <!-- 建立通知和切入点表达式的关系 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/> </aop:config>
测试:在业务层编写转账方法,不能在controller表现层编写
- bug:在表现层编写,事务不能起效果,因为事务切入点表达式是业务层
总结
配置文件:
web.xml:
- ContextLoaderListener监听器(加载Spring配置文件)、
- DispatcherServlet前端控制器(加载SpringMVC配置文件)、
- CharacterEncodingFilter(中文乱码问题)
<?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" metadata-complete="true"> <!--使用2.4以上的表头,不然会出现404--> <web-app> <display-name>Archetype Created Web Application</display-name> <!--配置applicationContext监听器,加载spring配置文件--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--配置加载类路径下的配置文件--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--配置前端控制器--> <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> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!--配置处理中文乱码问题--> <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> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
springMVC.xml:
- context:component-scan 开启注解扫描(只扫描mvc部分)、
- InternalResourceViewResolver 视图解析器
- mvc:default-servlet-handler排除静态资源过滤
- mvc:annotation-driven 开启MVC注解支持
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--开启注解扫描--> <context:component-scan base-package="cn.hm"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--配置视图解析器--> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/pages/"></property> <property name="suffix" value=".jsp"></property> </bean> <!--排除静态资源过滤问题--> <mvc:default-servlet-handler></mvc:default-servlet-handler> <!--开启Mvc注解支持--> <mvc:annotation-driven></mvc:annotation-driven> </beans>
applicationContext.xml:
- context:component-scan 开启注解扫描(排除mvc部分)
- 配置Bean:数据源 ComboPooledDataSource/druid/
- 配置Bean:工厂类对象 sqlSessionFactory
- 配置Bean:映射的包 MapperScannerConfigurer
- 配置Bean:平台事务管理器 DataSourceTransactionManager
- 配置事务通知:transactionManager
- 配置事务Aop增强:aop:config
<?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 http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--开启注解扫描--> <context:component-scan base-package="cn.hm"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--配置数据源c3p0--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="com.mysql.jdbc.Driver"></property> <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"></property> <property name="user" value="root"></property> <property name="password" value="1234"></property> </bean> <!--配置工厂对象--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> </bean> <!--配置映射的包--> <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> --> <property name="basePackage" value="cn.hm.dao"></property> </bean> <!--配置事务管理器--> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--配置事务通知--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="find*" read-only="true" propagation="SUPPORTS"/> <tx:method name="*" ></tx:method> </tx:attributes>/ </tx:advice> <!--配置aop增强--> <aop:config> <aop:pointcut id="pt1" expression="execution(* cn.hm.service.impl.*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"></aop:advisor> </aop:config> </beans>
sqlMapConfig.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> <typeAliases> <package name="cn.hm.dao"/> </typeAliases> </configuration>