目录
- SSM整合简介
 - 整合步骤
 - 先准备spring环境
 - 核心配置文件
 
- Spring整合Mybatis
 - 准备数据库和表
 - Spring管理数据库连接属性文件
 - Spring管理连接池
 - 实体类、mapper接口和映射文件
 - Spring管理SqlSessionFactory
 - Spring管理Mapper接口
 - Spring管理Servive层
 
- Spring整合SpringMVC
 - 准备web.xml
 - 准备SpringMVC.xml
 - 新建包和EmpController
 - web.xml配置监听器
 
- CRUD练习
 - 准备部门表
 - 实体类
 - controller
 - service
 - mapper
 - index.jsp
 - save.jsp
 
- 拦截器
 - 流程图
 - 自定义拦截器
 - 配置拦截器
 
SSM整合简介
SpringMVC本身是Spring的组件,Spring整合Mybatis即把Mybatis框架的核心类交给Spring管理(IOC)
 如Mybatis的SqlsessionFactory、Sqlsession和核心配置文件(四大金刚)
整合步骤
新建dynamic web project,修改默认输出的class路径,修改content directory名,勾选生成web.xml
 部署Tomcat
 导包:Spring、Spring测试、Servlet和jsp、数据库、Mybatis、Spring和Mybatis的整合包
先准备spring环境
核心配置文件
resources下创建核心配置文件applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
	<!-- 测试spring环境是否正常 -->
	<bean id="date" class="java.util.Date"></bean>
</beans>
 
测试能否正常使用核心配置文件中的bean
@ContextConfiguration("classpath:applicationContext.xml") // 加载核心配置文件
@RunWith(SpringJUnit4ClassRunner.class)// 使用spring的测试
public class SpringTest{
	@Autowired
	private Date date;
	
	@Test
	public void testName() throws Exception {
		System.out.println(date);
	}
}
 
Spring整合Mybatis
准备数据库和表
数据库1112下创建dept表
Spring管理数据库连接属性文件
准备属性文件,并交给Spring管理 - (原来是放在mybatis-config中然后由Resources读取)
 db.properties
db.username=root
db.password=root
db.url=jdbc:mysql:///1112
db.dirverClassName=com.mysql.jdbc.Driver
 
applicationContext.xml
	<!-- 把db.properties交给spring去管理 
	system-properties-mode="NEVER":如果有重名优先使用db.properties文件中的key -->
	<context:property-placeholder location="classpath:db.properties"
		system-properties-mode="NEVER" />
 
Spring管理连接池
通过连接池获取DataSource数据源
applicationContext.xml
	<!-- spring管理连接池 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="username" value="${db.username}"></property>
		<property name="password" value="${db.password}"></property>
		<property name="url" value="${db.url}"></property>
		<property name="driverClassName" value="${db.dirverClassName}"></property>
	</bean>
 
测试:SpringTest
	@Autowired
	private BasicDataSource dataSource;
	@Test
	public void testName() throws Exception {
		System.out.println(dataSource.getConnection());
	}
 
实体类、mapper接口和映射文件
domain下新建Emp
 代码略
mapper包下新建接口和映射文件
 EmpMapper
public interface EmpMapper {
	/**
	 * 查询所有
	*/
	List<Emp> findAll();
}
 
EmpMapper.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">
 <!-- namespace:名称空间:接口的全路径 -->
<mapper namespace="cn.ming.mapper.EmpMapper">
	<select id="findAll" resultType="cn.ming.domain.Emp">
		select *from emp
	</select>
</mapper>
 
Spring管理SqlSessionFactory
applicationContext.xml
	<!-- 将SqlSessionFactory交给Spring去管理 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 注入数据源,因为获取连接之后,才能打开会话 -->
		<property name="dataSource" ref="dataSource"></property>
		<!-- 配置别名 -->
		<property name="typeAliasesPackage" value="cn.ming.domain"></property>
		<!-- 加载所有的mapper文件 -->
		<property name="mapperLocations" value="classpath:cn/ming/mapper/*Mapper.xml"></property>
	</bean>
 
测试:SpringTest
	@Autowired
	private SqlSessionFactory factory;
	@Test
	public void testName() throws Exception {
		System.out.println(factory);
	}
 
Spring管理Mapper接口
applicationContext.xml
	<!-- 将Mapper接口交给Spring去管理,MapperScannerConfigurer:生成Mapper代理对象-->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<!-- 指定mapper接口的包路径 -->
		<property name="basePackage" value="cn.ming.mapper"></property>
	</bean>
 
测试:SpringTest
	@Autowired
	private EmpMapper mapper;// 代理对象
	@Test
	public void testName() throws Exception {
		List<Emp> list = mapper.findAll();
		list.forEach(System.out::println);
	}
 
Spring管理Servive层
service包下新建IEmpService
public interface IEmpService {
	
	List<Emp> findAll();
}
 
service.impl包下新建EmpServiceImpl,加上Service注解
@Service
public class EmpServiceImpl implements IEmpService {
	@Autowired
	private EmpMapper mapper;
	
	@Override
	public List<Emp> findAll() {
		// TODO Auto-generated method stub
		return mapper.findAll();
	}
}
 
applicationContext.xml
	<!-- 开启扫描包路径   service层 -->
	<context:component-scan base-package="cn.ming.service"></context:component-scan>
 
测试:SpringTest
	@Autowired
	private IEmpService service;
	@Test
	public void testName() throws Exception {
		List<Emp> list = service.findAll();
		list.forEach(System.out::println);
	}
 
Spring整合SpringMVC
准备web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>day41_ssm</display-name>
  
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <!-- 前端控制器 人家写好的servlet -->
    <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>
    <!-- Tomcat启动就初始化servlet -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <!-- 请求路径 -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  <!-- 我们用框架提供的支持UTF-8编码的过滤器 -->
  <filter>
    <filter-name>characterEncoding</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>
    <!--强制指定字符编码,即使request或response设置了字符编码,也会强制使用当前设置的,任何情况下强制使用此编码-->
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>
 
准备SpringMVC.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
	
	<!-- 开启扫描包路径 -->
	<context:component-scan base-package="cn.ming.controller" />
	
	<!-- 放行静态资源 -->
	<mvc:default-servlet-handler/>
	
	<!-- 使spring注解生效 @RequestMapping-->
 	<mvc:annotation-driven />
 	
 	<!-- 视图解析器  prefix+return+suffix = /WEB-INF/views/data.jsp -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".jsp"></property>	
	</bean>
	
	<!-- 上传解析器 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设置上传文件的最大尺寸为1MB -->
		<property name="maxUploadSize">
			<!-- spring el写法:1MB -->
			<value>#{1024*1024*20}</value>
		</property>
		<!-- 效果同上 -->
		<!-- <property name="maxUploadSize" value="1048576" /> -->
	</bean>
	
</beans>
 
新建包和EmpController
@Controller
public class EmpController {
	@Autowired
	private IEmpService service;
	
	@RequestMapping("/findAll")
	@ResponseBody // 返回json格式数据  不走视图解析器
	public List<Emp> findAll(){
		return service.findAll();
	}
}
 
web.xml配置监听器
原因:web容器启动时只加载了spring-mvc.xml,并没有加载applicationContext.xml
  <listener>
	  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
	<!-- 服务器启动的时候加载spring的核心配置文件 -->
  <context-param>
	  <param-name>contextConfigLocation</param-name>
	  <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
 
CRUD练习
见工程
准备部门表
略
实体类
略
controller
查询所有:查询所有后把数据放到request域中,jsp页面取值展示
 删除:删除后重定向到查询所有
 添加:跳往后端goSave,如果id为空跳转save页面,填值后跳往后端save,对象接收参数,如果没有隐藏域id就添加然后重定向到查询所有
 修改:跳往后端goSave,如果id有值,查询此条数据,向request域传值并跳转save页面,save页面取值回显,改数据后跳往后端save,有隐藏域id就修改然后重定向到查询所有
service
略
mapper
mapper.xml文件可以放到resources同路径目录下,编译后是一样的
index.jsp
相对路径与绝对路径
<a href="del?id=${dept.id }">删除</a>
<a href="/dept/del?id=${dept.id }">删除</a>
 
A标签都往后端跳,后端跳转页面
 添加与修改都是跳往后端同一个接口,然后跳转页面
save.jsp
略
拦截器
流程图

自定义拦截器
interceptor包下新建MyInterceptor
public class MyInterceptor implements HandlerInterceptor {
	// 到达处理器之前执行
	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		System.out.println("进入拦截器了....");
		return false;
	}
	// 处理器处理之后执行
	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		
	}
	// 响应到浏览器之前执行
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}
}
 
配置拦截器
springMVC.xml
	<!-- 配置拦截器组 -->
	<mvc:interceptors>
		<!-- 拦截器 -->
		<mvc:interceptor>
			<!-- 要拦截的配置,该配置必须写在不拦截的上面,/*拦截一级请求,/**拦截多级请求 -->
			<mvc:mapping path="/**"  />
			<!-- 设置不拦截的配置 -->
			<mvc:exclude-mapping path="/dept/*"/>
			<!-- 配置拦截器 -->
			<bean class="cn.ming.interceptor.MyInterceptor" />  
		</mvc:interceptor>
	</mvc:interceptors>
                


















