39.1 SSM 整合
39.1.1 搭建整合环境
整合说明: SSM整合可以使用多种方式,咱们会选择XML + 注解的方式
整合的思路
先搭建整合的环境
先把Spring的配置搭建完成
再使用Spring整合SpringMVC框架
最后使用Spring整合MyBatis框架
1.创建数据库和表结构
CREATE DATABASE ssm;
USE ssm;
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME VARCHAR(20),
money DOUBLE
);
package com. xww. domain;
import java. io. Serializable;
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
public Integer getId ( ) {
return id;
}
public void setId ( Integer id) {
this . id = id;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public Double getMoney ( ) {
return money;
}
public void setMoney ( Double money) {
this . money = money;
}
@Override
public String toString ( ) {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}' ;
}
}
package com. xww. dao;
import com. xww. domain. Account;
import org. apache. ibatis. annotations. Insert;
import org. apache. ibatis. annotations. Select;
import org. springframework. stereotype. Repository;
import java. util. List;
public interface AccountDao {
public List< Account> findAll ( ) ;
public void saveAccount ( Account account) ;
}
39.1.2 Spring框架代码的编写
1.项目中创建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: 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 = " com.xww" >
< context: exclude-filter type = " annotation" expression = " org.springframework.stereotype.Controller" />
</ context: component-scan>
</ beans>
package com. xww. test;
import com. xww. service. AccountService;
import org. junit. Test;
import org. springframework. context. ApplicationContext;
import org. springframework. context. support. ClassPathXmlApplicationContext;
public class TestSpring {
@Test
public void run1 ( ) {
ApplicationContext ac = new ClassPathXmlApplicationContext ( "classpath:applicationContext.xml" ) ;
AccountService as = ( AccountService) ac. getBean ( "accountService" ) ;
as. findAll ( ) ;
}
}
39.1.3 Spring整合SpringMVC框架
1.在web.xml中配置DispatcherServlet前端控制器与解决中文乱码
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
< web-app>
< display-name> Archetype Created Web Application</ display-name>
< servlet>
< servlet-name> dispatcherServlet</ servlet-name>
< servlet-class> org.springframework.web.servlet.DispatcherServlet</ servlet-class>
< 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>
2.创建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" >
< context: component-scan base-package = " com.xww" >
< context: include-filter type = " annotation" expression = " org.springframework.stereotype.Controller" />
</ context: component-scan>
< bean id = " internalResourceViewResolver" class = " org.springframework.web.servlet.view.InternalResourceViewResolver" >
< 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/**" />
< mvc: annotation-driven/>
</ beans>
3.创建AccountController类,编写方法,进行测试
package com. xww. controller;
import org. springframework. stereotype. Controller;
import org. springframework. web. bind. annotation. RequestMapping;
@Controller
@RequestMapping ( "/account" )
public class AccountController {
@RequestMapping ( "/findAll" )
public String findAll ( ) {
System. out. println ( "表现层:查询所有账户..." ) ;
return "list" ;
}
}
< a href = " account/findAll" > 测试查询</ a>
4.在项目启动的时候,就去加载applicationContext.xml的配置文件,在web.xml中配置
ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文件)。
< 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>
5.在controller中注入service对象,调用service对象的方法进行测试
package com. xww. controller;
import com. xww. service. AccountService;
import org. springframework. beans. factory. annotation. Autowired;
import org. springframework. stereotype. Controller;
import org. springframework. web. bind. annotation. RequestMapping;
@Controller
@RequestMapping ( "/account" )
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping ( "/findAll" )
public String findAll ( ) {
System. out. println ( "表现层:查询所有账户..." ) ;
return "list" ;
}
}
39.1.4 Spring整合MyBatis框
1.在项目中编写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>
< package name = " cn.itcast.dao" />
</ mappers>
</ configuration>
2.在AccountDao接口的方法上添加注解,编写SQL语句
package com. xww. dao;
import com. xww. domain. Account;
import org. apache. ibatis. annotations. Insert;
import org. apache. ibatis. annotations. Select;
import org. springframework. stereotype. Repository;
import java. util. List;
public interface AccountDao {
@Select ( "select * from account" )
public List< Account> findAll ( ) ;
@Insert ( "insert into account (name,money) values (#{name},#{money})" )
public void saveAccount ( Account account) ;
}
package com. xww. test;
import com. xww. dao. AccountDao;
import com. xww. domain. Account;
import org. apache. ibatis. io. Resources;
import org. apache. ibatis. session. SqlSession;
import org. apache. ibatis. session. SqlSessionFactory;
import org. apache. ibatis. session. SqlSessionFactoryBuilder;
import org. junit. Test;
import java. io. InputStream;
import java. util. List;
public class TestMyBatis {
@Test
public void run1 ( ) throws Exception {
InputStream in = Resources. getResourceAsStream ( "SqlMapConfig.xml" ) ;
SqlSessionFactory factory = new SqlSessionFactoryBuilder ( ) . build ( in) ;
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 ( ) ;
in. close ( ) ;
}
@Test
public void run2 ( ) throws Exception {
Account account = new Account ( ) ;
account. setName ( "熊大" ) ;
account. setMoney ( 400d ) ;
InputStream in = Resources. getResourceAsStream ( "SqlMapConfig.xml" ) ;
SqlSessionFactory factory = new SqlSessionFactoryBuilder ( ) . build ( in) ;
SqlSession session = factory. openSession ( ) ;
AccountDao dao = session. getMapper ( AccountDao. class ) ;
dao. saveAccount ( account) ;
session. commit ( ) ;
session. close ( ) ;
in. close ( ) ;
}
}
39.1.5 Spring整合MyBatis框架
1.把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中
< bean id = " dataSource" class = " com.mchange.v2.c3p0.ComboPooledDataSource" >
< property name = " driverClass" value = " com.mysql.jdbc.Driver" />
< property name = " jdbcUrl" value = " jdbc:mysql:///ssm" />
< property name = " user" value = " root" />
< property name = " password" value = " root" />
</ bean>
< bean id = " sqlSessionFactory" class = " org.mybatis.spring.SqlSessionFactoryBean" >
< property name = " dataSource" ref = " dataSource" />
</ bean>
< bean id = " mapperScanner" class = " org.mybatis.spring.mapper.MapperScannerConfigurer" >
< property name = " basePackage" value = " com.xww.dao" />
</ bean>
2.在AccountDao接口中添加@Repository注解
package com. xww. dao;
import com. xww. domain. Account;
import org. apache. ibatis. annotations. Insert;
import org. apache. ibatis. annotations. Select;
import org. springframework. stereotype. Repository;
import java. util. List;
@Repository
public interface AccountDao {
@Select ( "select * from account" )
public List< Account> findAll ( ) ;
@Insert ( "insert into account (name,money) values (#{name},#{money})" )
public void saveAccount ( Account account) ;
}
package com. xww. service. impl;
import com. xww. dao. AccountDao;
import com. xww. domain. Account;
import com. xww. service. AccountService;
import org. springframework. beans. factory. annotation. Autowired;
import org. springframework. stereotype. Service;
import java. util. List;
@Service ( "accountService" )
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
public List< Account> findAll ( ) {
System. out. println ( "业务层:查询所有账户..." ) ;
return accountDao. findAll ( ) ;
}
public void saveAccount ( Account account) {
System. out. println ( "业务层:保存帐户..." ) ;
accountDao. saveAccount ( account) ;
}
}
package com. xww. test;
import com. xww. service. AccountService;
import org. junit. Test;
import org. springframework. context. ApplicationContext;
import org. springframework. context. support. ClassPathXmlApplicationContext;
public class TestSpring {
@Test
public void run1 ( ) {
ApplicationContext ac = new ClassPathXmlApplicationContext ( "classpath:applicationContext.xml" ) ;
AccountService as = ( AccountService) ac. getBean ( "accountService" ) ;
as. findAll ( ) ;
}
}
5.在applicationContext.xml中配置Spring的声明式事务管理
< bean id = " transactionManager" class = " org.springframework.jdbc.datasource.DataSourceTransactionManager" >
< property name = " dataSource" ref = " dataSource" />
</ 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: config>
< aop: advisor advice-ref = " txAdvice" pointcut = " execution(* com.xww.service.impl.*ServiceImpl.*(..))" />
</ aop: config>
@RequestMapping ( "/save" )
public void save ( Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
accountService. saveAccount ( account) ;
response. sendRedirect ( request. getContextPath ( ) + "/account/findAll" ) ;
return ;
}