SSM 整合笔记
1 环境准备
1.1 创建数据库和表结构
create database ssm;
use ssm;
create table account(
id int primary key auto_increment,
name varchar(20),
money double
);
1.2 创建 Maven 工程
1.3 导入坐标
<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>
<!--jar包版本锁定-->
<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>
1.4 编写实体类
/**
* 账户实体类
*/
public class Account implements Serializable {
private int id;
private String name;
private Double money;
public int getId() {
return id;
}
public void setId(int 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 +
'}';
}
}
1.5 编写业务层接口
/**
* 账户service接口
*/
public interface AccountService {
// 查询所有账号信息
public List<Account> findAll();
// 保存账户信息
public void saveAccount(Account account);
}
/**
* 账户service接口实现类
*/
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
AccountDao accountDao;
@Override
public List<Account> findAll() {
System.out.println("业务层: 查询所有账户信息..");
return accountDao.findAll();
}
@Override
public void saveAccount(Account account) {
System.out.println("业务层: 保存账户信息..");
accountDao.saveAccount(account);
}
}
1.6 编写持久层接口
/**
* 账户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);
}
1.2 整合步骤
2.1 Spring框架代码的编写
2.1.1 第一步:编写 spring 配置文件并导入约束
在ssm_web项目中创建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">
<!-- 开启注解扫描,要扫描的是service和dao层的注解,要忽略web层注解,因为web层让SpringMVC框架
去管理 -->
<context:component-scan base-package="org.example">
<!-- 配置要忽略的注解 -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
2.1.1 编写测试方法,进行测试
public class TestSpring {
@Test
public void run1(){
// 加载配置方法
ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
// 获取对象
AccountService accountService = (AccountService)ac.getBean("accountService");
// 调用方法
accountService.findAll();
}
}
2.2 搭建和测试SpringMVC的开发环境
2.2.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>
<!-- 配置解决中文乱码的过滤器 -->
<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配置文件 -->
<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-app>
2.2.2 编写 SpringMVC 的配置文件
<?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的注解,别的不扫描 -->
<context:component-scan base-package="org.example">
<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 />
</beans>
2.2.3 编写 Controller 和 jsp
jsp 代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="account/findAll">测试</a><br/>
</body>
</html>
控制器代码:
@Override
public List<Account> findAll() {
System.out.println("业务层: 查询所有账户信息..");
return "null"
}
2.3 整合 Spring 和 和 SpringMVC
2.3.1 在web.xml中配置监听器实现启动服务创建容器
<!-- 配置加载类路径的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置Spring的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
2.4 搭建和测试MyBatis的环境
2.4.1 在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://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!-- 引入配置文件 -->
<mappers>
<!-- <mapper class="cn.itcast.dao.AccountDao"/> -->
<!-- 该包下所有的dao接口都可以使用 -->
<package name="org.example.dao"/>
</mappers>
</configuration>
2.4.2 在AccountDao接口的方法上添加注解,编写SQL语句
/**
* 账户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);
}
2.4.3 编写测试的方法
public class TestMyBatis {
/**
* 测试查询
* @throws Exception
*/
@Test
public void run1() throws Exception {
// 加载配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 创建SqlSession
SqlSession session = factory.openSession();
// 获取到代理对象
AccountDao dao = session.getMapper(AccountDao.class);
// 查询所有信息
List<Account> accounts = dao.findAll();
for(Account account: accounts){
System.out.println(account);
}
// 关闭资源
session.close();
in.close();
}
/**
* 测试保存
* @throws Exception
*/
@Test
public void run2() throws Exception {
Account account = new Account();
account.setName("熊大");
account.setMoney(3000d);
// 加载配置文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
// 创建SqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
// 创建SqlSession
SqlSession session = factory.openSession();
// 获取到代理对象
AccountDao dao = session.getMapper(AccountDao.class);
// 查询所有信息
dao.saveAccount(account);
// 提交事务
session.commit();
// 关闭资源
session.close();
in.close();
}
}
2.5 Spring整合MyBatis框架
2.5.1 把SqlMapConfig.xml配置文件中的内容配置到applicationContext.xml配置文件中
<!--Spring整合MyBatis框架-->
<!--配置连接池-->
<!-- 配置C3P0的连接池对象 -->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!--配置SqlSessionFactory工厂-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 配置扫描dao的包 -->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="org.example.dao"/>
</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="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置 aop -->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut expression="execution(* org.example.service.impl.*.*(..))"
id="pt1"/>
<!-- 建立通知和切入点表达式的关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
2.5.2 在AccountDao接口中添加@Repository注解
/**
* 账户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);
}
2.5.3 在service中注入dao对象,进行测试
/**
* 账户service接口实现类
*/
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
AccountDao accountDao;
@Override
public List<Account> findAll() {
System.out.println("业务层: 查询所有账户信息..");
return accountDao.findAll();
}
@Override
public void saveAccount(Account account) {
System.out.println("业务层: 保存账户信息..");
accountDao.saveAccount(account);
}
}
2.5.4 配置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="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置 aop -->
<aop:config>
<!-- 配置切入点表达式 -->
<aop:pointcut expression="execution(* org.example.service.impl.*.*(..))"
id="pt1"/>
<!-- 建立通知和切入点表达式的关系 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
2.5.5 测试保存帐户的方法
jsp 代码:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="account/findAll">测试</a><br/>
<h3>测试保存</h3>
<form action="account/save" method="post">
姓名:<input type="text" name="name"/><br/>
金额:<input type="text" name="money"/><br/>
<input type="submit" value="提交"/><br/>
</form>
</body>
</html>
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} ${account.money}<br/>
</c:forEach>
${list}
</body>
</html>
controller 代码:
/**
* 账户控制器(web层)
*/
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
AccountService accountService;
@RequestMapping("findAll")
public String findAll(Model model){
System.out.println("表现层: 查询所有账户...");
List<Account> list = accountService.findAll();
model.addAttribute("list",list);
return "list";
}
@RequestMapping("save")
public void dave(Account account, HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("表现层: 保存账户信息...");
accountService.saveAccount(account);
response.sendRedirect(request.getContextPath()+ "/account/findAll");
return;
}
}
网友评论