SSM整合
前面我们学习了spring 、springmvc和 mybatis,今天我们来整合一下,集成开发环境,让他们能够一起为我们工作;
SSM;Spring+SpringMVC+MyBatis
1、导包
1)、Spring
【aop核心】
com.springsource.net.sf.cglib-2.2.0.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
spring-aspects-4.0.0.RELEASE.jar
【ioc核心】
commons-logging-1.1.3.jar
spring-aop-4.0.0.RELEASE.jar
spring-beans-4.0.0.RELEASE.jar
spring-context-4.0.0.RELEASE.jar
spring-core-4.0.0.RELEASE.jar
spring-expression-4.0.0.RELEASE.jar
【jdbc核心】
spring-jdbc-4.0.0.RELEASE.jar
spring-orm-4.0.0.RELEASE.jar
spring-tx-4.0.0.RELEASE.jar
【测试】
spring-test-4.0.0.RELEASE.jar
2)、SpringMVC
【ajax】
jackson-annotations-2.1.5.jar
jackson-core-2.1.5.jar
jackson-databind-2.1.5.jar
【数据校验】
hibernate-validator-5.0.0.CR2.jar
hibernate-validator-annotation-processor-5.0.0.CR2.jar
classmate-0.8.0.jar
jboss-logging-3.1.1.GA.jar
validation-api-1.1.0.CR1.jar
【上传下载】
commons-fileupload-1.2.1.jar
commons-io-2.0.jar
【jstl-jsp标准标签库】
jstl.jar
standard.jar
【验证码】
kaptcha-2.3.2.jar
【springmvc核心】
spring-web-4.0.0.RELEASE.jar
spring-webmvc-4.0.0.RELEASE.jar
3)、MyBatis
【mybatis核心】
mybatis-3.4.1.jar
mybatis-spring-1.3.0.jar【和Spring整合包】
【ehcache整合】
ehcache-core-2.6.8.jar
mybatis-ehcache-1.0.3.jar
log4j-1.2.17.jar
slf4j-api-1.7.21.jar
slf4j-log4j12-1.7.21.jar
4)、其他的
mysql-connector-java-5.1.37-bin.jar
c3p0-0.9.1.2.jar
jsqlparser-0.9.5.jar
mybatis-spring-1.3.0.jar
2、写配置
0)、web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>7.SSM</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 配置Spring容器启动: -->
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!--指定spring配置文件位置 -->
<param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置springmvc的前端控制器 -->
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springDispatcherServlet</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>
<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>
<!-- 支持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>
1)、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" xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd 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-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
- <!-- Spring除过控制器不要,剩下的业务逻辑组件都要,包括dao,包括service
-->
- <context:component-scan base-package="com.atguigu">
- <!-- 扫描排除不写use-default-filters="false"
-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
- <!-- 0、导入外部配置文件
-->
<context:property-placeholder location="classpath:dbconfig.properties" />
- <!-- 1、配数据源
-->
- <bean id="ds" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClass" value="${jdbc.driverClass}" />
<property name="jdbcUrl" value="${jdbc.jdbcUrl}" />
<property name="maxPoolSize" value="${jdbc.maxPoolSize}" />
<property name="minPoolSize" value="${jdbc.minPoolSize}" />
</bean>
- <!-- 2、配置JdbcTemplate操作数据库。pass
-->
- <!-- 3、配置使用mybatis操作数据库
-->
- <!-- 可以根据配置文件得到sqlSessionFactory
-->
- <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
- <!-- 指定配置文件位置
-->
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
<property name="dataSource" ref="ds" />
- <!-- 指定xml映射文件的位置
-->
<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml" />
</bean>
- <!-- 我们要把每一个dao接口的实现加入到ioc容器;
-->
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
- <!-- 指定dao接口所在的包
-->
<property name="basePackage" value="com.atguigu.dao" />
</bean>
- <!-- <mybatis-spring:scan base-package="com.atguigu.dao"/>
-->
- <!-- 4、配置事务控制;配置事务管理器,让他控制住数据源里面的链接的关闭和提交
-->
- <bean id="tm" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="ds" />
</bean>
- <!-- 5、基于xml配置,配置事务;哪些方法切入事务还要写切入点表达式
-->
- <aop:config>
- <!-- 配置切入点表达式
-->
<aop:pointcut expression="execution(* com.atguigu.service.*.*(..))" id="txPoint" />
<aop:advisor advice-ref="myTx" pointcut-ref="txPoint" />
</aop:config>
- <!-- 6、配置事务增强、事务属性、事务建议
transaction-manager="tm":指定要配置的事务管理器的id
-->
- <tx:advice id="myTx" transaction-manager="tm">
- <!-- 配置事务属性
-->
- <tx:attributes>
<tx:method name="*" rollback-for="java.lang.Exception" />
<tx:method name="get*" read-only="true" />
- <!-- <tx:method name="insertEmp" isolation="READ_UNCOMMITTED"/>
-->
</tx:attributes>
</tx:advice>
</beans>
2)、springmvc的配置 applicationContext-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
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-4.0.xsd">
<!-- SpringMVC只扫描控制器;禁用默认的规则 -->
<context:component-scan base-package="com.atguigu" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--配置文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="#{1024*1024*20}"></property>
</bean>
<!-- 扫静态资源 -->
<mvc:default-servlet-handler/>
<!-- 扫动态 -->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
3)、 mybatis的配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration (View Source for full doctype...)>
- <configuration>
- <settings>
<setting name="lazyLoadingEnabled" value="true" />
<setting name="aggressiveLazyLoading" value="false" />
<setting name="cacheEnabled" value="true" />
</settings>
- <plugins>
<plugin interceptor="com.github.pagehelper.PageInterceptor" />
</plugins>
</configuration>
注意:整合的关键配置就是在spring的配置文件中添加了下面这段配置,并且将mybatis原有的数据源与类配置删除;
<!--2、配置JdbcTemplate操作数据库。pass -->
<!--3、配置使用mybatis操作数据库 -->
<!-- 可以根据配置文件得到sqlSessionFactory -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 指定配置文件位置 -->
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml"></property>
<property name="dataSource" ref="ds"></property>
<!-- 指定xml映射文件的位置 -->
<property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"></property>
</bean>
<!-- 我们要把每一个dao接口的实现加入到ioc容器; -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定dao接口所在的包 -->
<property name="basePackage" value="com.atguigu.dao"></property>
</bean>
4)、其他小家伙的配置 (如EHcache等)
1、整合步骤:
1)、导入整合包;mybatis-spring-1.3.0.jar(能将dao的实现加入到容器中,已经写在上面的倒包列表中了)
接下来就可以测试了 。。。
首先创建一个动态的web项目
employeeController.java
package com.gome.controller;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.gome.been.employee;
import com.gome.dao.employeeDao;
@Controller
public class employeeController{
@Autowired
employeeDao employeeDao;
@Autowired
SqlSessionFactory sqlSessionFactory;
@RequestMapping(value="/getEmp")
public String getEmp(@RequestParam(value="id", defaultValue="1") int id, Model model){
System.out.println("f w controller!!!");
System.out.println(employeeDao);
employee employee;
if(employeeDao!=null){
employee = employeeDao.getEmpById(id);
System.out.println(employee);
model.addAttribute("emp", employee);
}
if(sqlSessionFactory!=null){
SqlSession sqlSession = sqlSessionFactory.openSession();
System.out.println("sqlSession:"+sqlSession);
employeeDao = sqlSession.getMapper(employeeDao.class);
System.out.println("employeeDao:"+employeeDao);
}
return "success";
};
}
employeeDao.java
package com.gome.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.MapKey;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.gome.been.employee;
@Repository
public interface employeeDao {
//@Select(value = { "select * from employeedao where id=#{0};" })
public employee getEmpById(int id);
public List<employee> getEmpByAge(int age);
public int insert(employee employee);
public Map<String, Object> getEmpByIdReturnMap(int id);
@MapKey(value="id")
public Map<Integer, Object> getEmpByAgeReturnMap(int age);
}
这里有一点需要说明: 为什么controller的文件上方有显示S,表示已经将该类的对象添加到ioc容器中了,而dao的相关文件上方没有显示呢???
因为dao层是我们使用mybatis访问数据库提供的接口类,我们应该将dao全部添加到mybatis中,并且将mybatis中的所有dao文件都交给spring的ioc容器统一管理,MapperScannerConfigurer是spring和mybatis整合的mybatis-spring jar包中提供的一个类,作用就是给mybatis添加dao并放在spring的ioc中统一管理,所以就算使用注解 @Repository也无法在上图中显示添加到ioc容器中,因为dao是通过mybatis间接添加到ioc中的,所以上边的employeeDao.java中的 @Repository注解完全无用,我们在employeeController.java中的@Autowired
employeeDao employeeDao;之所以可以使用是因为我们在spring的配置文件中向ioc添加了mybatis的配置和mybatis指定加载的所有类,mybatis指定加载的类就是到;
employeeDao.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.gome.dao.employeeDao">
<select id="getEmpById" resultType="com.gome.been.employee" >
select * from employeedao where id=#{0};
</select>
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
<selectKey order="BEFORE" resultType="int" keyProperty="sax">
select MAX(sax)+1 from employeedao;
</selectKey>
INSERT INTO employeedao(id, emp_name, age, sax) VALUES(#{id}, #{empName}, #{age}, #{sax});
</insert>
<select id="getEmpByAge" resultType="com.gome.been.employee">
select * from employeedao where age=#{age}
</select>
<select id="getEmpByIdReturnMap" resultType="map" >
select * from employeedao where id=#{id};
</select>
<select id="getEmpByAgeReturnMap" resultType="com.gome.been.employee">
select * from employeedao where age=#{age}
</select>
</mapper>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="getEmp?id=2">hahahahah</a>
</body>
</html>
运行:
最后将ssm整合的工程代码放在这里,用于下载,方便需要时使用:
https://download.youkuaiyun.com/download/qq_25106373/10934483