资料区
ssm整合笔记:SpringMVC第三天【随堂笔记】.pdf
整个工程文件(自己的):ssm.zip
ssm整合说明
通过Spring去整合Mybatis或SpringMVC并进行逐个测试
一、搭建整合环境
1、 整合说明:SSM整合可以使用多种方式
选择XML + 注解的方式
2、 整合的思路
- 先搭建整合的环境
2. 先把Spring的配置搭建完成
3. 再使用Spring整合SpringMVC框架
4. 最后使用Spring整合MyBatis框架
3、创建数据库和表结构
create database ssm;use ssm;create table account(id int primary key auto_increment,name varchar(20),money double);


4、创建Maven工程文件



archetypeCatalog
internal

5、引入坐标(pom.xml)
<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>
<!--SpringMVC-->
<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>
<!--jdbc模板技术-->
<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>
<!--mysql驱动jar包-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
<!--servlet与jsp-->
<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>
<!--jstl:想写EL表达式,jstl-->
<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 -->
<!--mybatis使用到的jar包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!--spring整合mybatis需要用到-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!--c3p0的连接池-->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
6、创建文件夹、包以及编写类与接口
包含表现层、业务层以及持久层
AccountController.java
package com.changlu.controller;
/**
* 账户web
* @anthor changlu
* @create 2020-10-03-17:07
*/
public class AccountController {
}
IAccountDao.java
package com.changlu.dao;
import com.changlu.domain.Account;
import java.util.List;
/**
* 账户dao接口
* @anthor changlu
* @create 2020-10-03-17:00
*/
public interface IAccountDao {
//查询所有账户信息
public List<Account> findAll();
//保存账户信息
public void saveAccount(Account account);
}
Account.java
package com.changlu.domain;
import java.io.Serializable;
/**
* @anthor changlu
* @create 2020-10-03-16:59
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
...set/get方法以及toString()方法
}
IAccountService.java
package com.changlu.service;
import com.changlu.domain.Account;
import java.util.List;
/**
* @anthor changlu
* @create 2020-10-03-17:05
*/
public interface IAccountService {
//查询所有账户信息
public List<Account> findAll();
//保存账户信息
public void saveAccount(Account account);
}
AccountServiceImpl.java
package com.changlu.service.impl;
import com.changlu.domain.Account;
import com.changlu.service.IAccountService;
import java.util.List;
/**
* @anthor changlu
* @create 2020-10-03-17:06
*/
public class AccountServiceImpl implements IAccountService{
@Override
public List<Account> findAll() {
System.out.println("业务层:查询所有的账户信息...");
return null;
}
@Override
public void saveAccount(Account account) {
System.out.println("业务层:保存账户...");
}
}
7、添加日志
二、Spring框架代码的编写
创建配置文件


1、编写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="com.changlu">
<!--配置Controller注解不扫描,expression是全限定类名-->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
2、在Service类上使用注解,进行测试(创建测试类)
AccountServiceImpl.java

创建文件目录,测试bean实例

package com.changlu.test;
import com.changlu.domain.Account;
import com.changlu.service.IAccountService;
import com.changlu.service.impl.AccountServiceImpl;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @anthor changlu
* @create 2020-10-03-17:37
*/
public class TestSpring {
@Test
public void run(){
//1. 加载Spring配置文件
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
//2. 获取配置创建的对象
IAccountService accountService = context.getBean("accountService", AccountServiceImpl.class);
System.out.println(accountService);//打印实例
//3. 调用方法
accountService.findAll();
accountService.saveAccount(new Account());
}
}

Spring框架搭建成功
**
三、Spring整合SpringMVC框架
1、搭建与测试SpringMVC的开发环境
① web.xml中配置前端控制器以及过滤器(解决中文乱码问题)

配置前端控制器
<!--配置前端控制器-->
<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>
配置解决中文乱码过滤器
<!--解决中文乱码过滤器-->
<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



<?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="com.changlu">
<!--只扫描这个注解-->
<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/**"/>
<!--开启springmvc注解的支持-->
<mvc:annotation-driven/>
</beans>
③ 测试SpringMVC的框架搭建是否成功
1、编写index.jsp和list.jsp编写(发送与跳转页面)

index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="account/findAll">点击跳转</a>
</body>
</html>
list.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>查询所有账户...</h3>
</body>
</html>
2、创建AccountController类的方法,进行测试

@Controller
@RequestMapping("/account")
public class AccountController {
@RequestMapping("/findAll")
public String findAll(){
System.out.println("查询所有用户...");
return "list";
}
}
3、配置Tomcat服务器以及测试


测试

SpringMVC框架搭建成功!
**
2、Spring整合SpringMVC的框架
如何配置Spring配置文件
对于之前测试spring框架是否搭建成功,是在一个测试类中加载对应的spring配置文件,在搭建了springmvc框架(其中springmvc.xml在配置前端控制器时进行加载),对应spring的配置文件并没有进行配置,那我们如何在Tomcat服务器启动时进行自动配置呢?
我们可以通过下方提供的监听器类来进行配置:
① web.xml中配置监听器(间接配置spring的配置文件)

<!--配置spring的监听器,默认只加载WEB-INF目录下的applictionContext.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>
② 在controller中对属性进行注解注入,测试
AccountController.java

使用注解@Autowired来根据类型自动装配
测试



Spring整合SpringMVC框架成功!
四、Spring整合Mybatis框架
1、搭建Mybatis框架,并进行测试
① 创建Mybatis的主配置文件(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="123456"/>
</dataSource>
</environment>
</environments>
<!--引入映射配置文件-->
<mappers>
<!--<mapper class="com.changlu.dao.IAccountDao"/>-->
<package name="com.changlu.dao"/>
</mappers>
</configuration>
② 创建测试类进行测试(查询与保存)
首先我们再数据库中插入两条记录

编写测试类,测试查询方法

package com.changlu.test;
/**
* @anthor changlu
* @create 2020-10-04-14:29
*/
public class TestMybatis {
@Test
public void run1() throws Exception {
//1、加载mybatis配置文件(获取流)
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
//2、创建sqlSessionFactory对象
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
//3、创建sqlSession对象
SqlSession session = factory.openSession();
//4、获取到代理对象
IAccountDao dao = session.getMapper(IAccountDao.class);
//5、查询所有数据信息
List<Account> list = dao.findAll();
for(Account account:list){
System.out.println(account);
}
//关闭资源
session.close();
is.close();
}
}

保存一条记录


2、Spring整合Mybatis框架
① Spring主配置文件(applicationContext.xml)进行配置
目的:把SqlMapConfifig.xml配置文件中的内容配置到applicationContext.xml配置文件中
通过Spring的IOC容器来配置①连接池
配置Mybatis提供的②SqlSessionFactory(注入连接池属性)与③MapperScannerConfigurer(配置对应的接口)
<!--Spring整合Mybatis框架-->
<!--配置连接池-->
<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="123456"/>
</bean>
<!--配置SqlSessionFactory-->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--配置AccountDao接口所在包-->
<bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.changlu.dao"/>
</bean>
这些配置与之前的Mybatis主配置文件其实大致相同,只不过交由IOC容器处理,此时我们可以将Mybatis的主配值文件删除
② 对Dao接口、Service类以及Controller进行更改

为Dao接口添加注解@Repository进行依赖注入
@Repository
public interface IAccountDao {
//查询所有账户信息
@Select("select * from account")
public List<Account> findAll();
//保存账户信息
@Insert("insert into account(name,money) values(#{name},#{money})")
public void saveAccount(Account account);
}
Service类中添加注解自动装配dao代理类,并执行方法

AccountController.java来将查询到的数据返回到视图层

③ 跳转页面显示查询数据,进行测试


测试效果:


3、配置事务
① 在Spring主配置文件(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增强-->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.changlu.service.impl.*ServiceImpl.*(..))"/>
</aop:config>
配置事务管理:是根据spring提供的进行创建bean对象,并注入dataSource
配置事务通知,对于所有find开头的方法,设置为只读属性;对于所有方法都设置为默认,默认就是可重复读
配置AOP增强:将对应事务配置到service类中
② 更改index.jsp页面与Controller类中增加方法
index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--<a href="account/findAll">点击跳转</a>--%>
<h1>测试发送请求</h1>
<form action="account/saveAccount" method="post">
姓名:<input type="text" name="name">
金额:<input type="text" name="money">
<input type="submit" value="提交">
</form>
</body>
</html>
AccountController.java中增加保存方法

创建saveAccount方法来接收参数并进行重定向转发
③ 进行测试


整理者:长路 时间:2020/10/4


