目录
标题搭建整合SSM环境
整合说明:SSM整合可以使用多种方式,咱们会选择XML + 注解的方式
整合的思路
-
先搭建整合的环境
-
先把Spring的配置搭建完成
-
再使用Spring整合SpringMVC框架
-
最后使用Spring整合MyBatis框架
自己随便建个数据库一会测试用
create database ssm; use ssm;
create table account(
id int primary key auto_increment,
name varchar(20),
money double
);
1 .导入依赖(总的整合依赖)
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<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>
<!--spring整合junit-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 为JDBC、Hibernate、JDO、JPA等提供的一致的声明式和编程式事务管理-->
<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 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>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.4</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>
</dependencies>
<build>
<finalName>ssm</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
2 配置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,controller不需要Spring框架去处理-->
<context:component-scan base-package="cn.itcast">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
建立目录结构
AccountDao.java
@Repository //持久层注解
public interface AccountDao {
// 查询所有账户
//@Select("select * from account") //还没有配置mybatis所以暂时注释起来
public List<Account> findAll();
}
Service.java
@Service("accountService")
public class AccountServiceImpl implements AccountService{
@Autowired
private AccountDao accountDao;
public void findAll() {
System.out.println("业务层:查询所有账户...");
//return accountDao.findAll(); //还没有配置mybatis所以暂时注释起来
}
}
log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE debug info warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE
# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE
# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
TestSpring.java
package cn.itcast.test;
import cn.itcast.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpring {
@Test
public void run1(){
//1 加载配置
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
//2 获取对象
AccountService accountService = (AccountService) ac.getBean("accountService");
//3 调用方法
accountService.findAll();
}
}
结果:
表现层查询出页面...
3 搭建和测试 SpringMVC的开发环境
- 在web.xml中配置DispatcherServlet前端控制器
web.xml
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- 1。 在web.xml中配置DispatcherServlet前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加载springmvc.xml配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 启动服务器创建该servlet-->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 配置前端控制器映射-->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 2. 在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>
</web-app>
- 创建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">
<!-- 1. 扫描controller的注解,其他不扫描-->
<context:component-scan base-package="cn.itcast">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 2. 配置视图解析器对象 记得在"/WEB-INF/pages/创建一个jsp页面 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 3. 过滤静态资源-->
<mvc:resources mapping="/css/**" location="/css/"></mvc:resources>
<mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
<mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
<!-- 4. 开启springmvc注解的支持-->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
3 .创建AccountController.java类,编写方法,进行测试
@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAll")
public String findAll(){
System.out.println("表现层查询出页面...");
return "list";
}
}
4 . 在index页面访问测试
<a href="account/findAll">查询所有</a>
4 Spring整合SpringMVC的框架
目的:在controller中能成功的调用service对象中的方法。
在项目启动的时候,就去加载applicationContext.xml的配置文件,在web.xml中配置
ContextLoaderListener监听器(该监听器只能加载WEB-INF目录下的applicationContext.xml的配置文
件)
1 . ! 在配置前端控制器dispatcherServlet前配置监听器
<!-- 配置spring的监听器,默认只加载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>
2 .在AccountController使用自动注入
业务层:查询所有账户...
表现层查询出页面...
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(){
accountService.findAll();
System.out.println("表现层查询出页面...");
return "list";
}
}
结果:
业务层:查询所有账户...
表现层查询出页面...
其实不用配置监听器也可以调用,但为啥要配置呢??:
1 如果只有 Spring mvc 的一个 Servlet,listener 可以不用。
2 但是如果用了Shiro 等,Shiro 用到的 Spring 的配置必须在 listener 里加载。
3 一般 Dao, Service 的 Spring 配置都会在 listener 里加载,因为可能会在多个 Servlet 里用到,因为父子 Context 的可见性问题,防止重复加载所以在 listener 里加载。
所以,有时可用可不用,有时必用,具体看情况
5 搭建和测试 MyBatis框架的开发环境
- 搭建和测试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">
<!--mybatis核心配置-->
<configuration>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 使用的是注解 -->
<mappers>
<!-- <mapper class="cn.itcast.dao.AccountDao"></mapper>-->
<package name="cn.itcast.dao"/>
</mappers>
</configuration>
AccountDao.java 加入mybatis注解
package cn.itcast.dao;
import cn.itcast.modle.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 帐户dao接口
*/
@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);
}
创建测试 TestMybatis.java
package cn.itcast.test;
import cn.itcast.dao.AccountDao;
import cn.itcast.modle.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{
//1 加载配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//2 创建sqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3 创建Sqlsession对象
SqlSession session = factory.openSession();
//5 获取到代理对象
AccountDao accountDao = session.getMapper(AccountDao.class);
//6 查询数据
List<Account> accountList = accountDao.findAll();
for (Account a :accountList) {
System.out.println(a);
}
//7 关闭资源
session.close();
in.close();
}
}
结果:
Account{id=1, name='小明', money=11.0}
Account{id=2, name='小刚', money=44.0}
6 Spring整合MyBatis框架
- 目的:把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中(可以删掉SqlMapConfig.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">
<!--开启注解的扫描,希望处理service和dao,controller不需要Spring框架去处理-->
<context:component-scan base-package="cn.itcast">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置driud的连接池对象-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/ssm"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</bean>
<!-- 配置Sqlsession的工厂-->
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 配置扫描dao的包-->
<bean id="mapperSacnner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.itcast.dao"></property>
</bean>
</beans>
-
在AccountDao接口中添加@Repository注解
-
在service中注入dao对象,进行测试
AccountDao.java
package cn.itcast.dao;
import cn.itcast.modle.Account;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 帐户dao接口
*/
@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);
}
Service.java
package cn.itcast.service.impl;
import cn.itcast.dao.AccountDao;
import cn.itcast.modle.Account;
import cn.itcast.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);
}
}
AccountController.java
package cn.itcast.controller;
import cn.itcast.modle.Account;
import cn.itcast.service.AccountService;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* 帐户web
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/findAll")
public String findAll(Model model){
System.out.println("表现层:查询所有账户...");
//调用service的方法
List<Account> list = accountService.findAll();
model.addAttribute("list",list);
return "list";
}
/**
* 保存
* @return
*/
@RequestMapping("/save")
public void save(Account account, HttpServletRequest request, HttpServletResponse response) throws IOException {
accountService.saveAccount(account);
//请求的项目路径+/account/findAll
response.sendRedirect(request.getContextPath()+"/account/findAll");
return;
}
}
编写一个展示数据库信息的页面
list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>查询所有信息</h3>
<c:forEach items="${list}" var="account">
${account.name}
</c:forEach>
</body>
</html>
4 . 在index页面访问测试
<a href="account/findAll">查询所有</a>
结果:
小明 小刚 (数据库中存的数据)
-
配置Spring的声明式事务管理
在applicationContext.xml中的beans中加入事务配置
<!-- 配置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增强-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.service.impl.*ServiceImpl.*(..))"/>
</aop:config>
-
配置Spring的声明式事务管理
在applicationContext.xml中的beans中加入事务配置
<!-- 配置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增强-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* cn.itcast.service.impl.*ServiceImpl.*(..))"/>
</aop:config>