# Spring基本介绍
Spring是分层的Java SE/EE应用,一站式轻量级开源框架,以 IoC(Inverse Of Control:反转控制)和 AOP(Aspect Oriented Programming:面向切面编程)为内核。
提供了展现层 SpringMVC 和持久层 Spring JDBC 以及业务层事务管理等众多的企业级应用技术,还能整合众多第三方框架和类库,逐渐成为使用最多的Java EE 企业应用开源框架。
- 分层:它可以针对web/service/dao各个层次提供解决方案
- 一站式:Spring可以一站式解决企业开发过程中所有的问题,可以管理整个项目
- Spring核心的框架:SpringFramework,至于SpringBoot、SpringCloud都是它的衍生框架
# 优势特点
方便解耦,简化开发
通过 Spring提供的 IoC容器,可以将对象间的依赖关系交由 Spring进行控制,避免硬编码所造成的过度程序耦合。用户也不必再为单例模式类、属性文件解析等这些很底层的需求编写代码,可以更专注于上层的应用AOP 编程的支持(动态代理)
通过 Spring的 AOP 功能,方便进行面向切面的编程,许多不容易用传统OOP 实现的功能可以通过 AOP 轻松应付声明式事务的支持
可以将我们从单调烦闷的事务管理代码中解脱出来,通过声明式方式灵活的进行事务的管理,提高开发效率和质量方便程序的测试
可以用非容器依赖的编程方式进行几乎所有的测试工作,测试不再是昂贵的操作,而是随手可做的事情方便集成各种优秀框架
Spring可以降低各种框架的使用难度,提供了对各种优秀框架(Struts、Hibernate、Hessian、Quartz等)的直接支持降低 JavaEE API 的使用难度
Spring对 JavaEE API(如 JDBC、JavaMail、远程调用等)进行了薄薄的封装层,使这些 API 的使用难度大为降低Spring源码是经典学习范例
Spring的源代码设计精妙、结构清晰、匠心独用,处处体现着大师对Java 设计模式灵活运用以及对 Java技术的高深造诣。它的源代码无意是 Java 技术的最佳实践的范例
# 核心概念
控制反转Ioc(Inversion of Control)
所有对象的创建都不是由自己去new,而是将创建对象的权利反转给Spring,我们只是从Spring容器里面去拿,此过程中对象创建控制权由程序转移到外部,此思想称为控制反转Bean对象
Ioc容器负责对象的创建、初始化等一系列工作,被创建或被管理的对象在IOC容器中统称为Bean依赖注入DI(Dependency Injection)
在容器中建立bean与bean之间的依赖关系的整个过程,称为依赖注入
# 体系结构
- Test:测试
- Core Container:Spring的核心容器
- Bean Core 是实现IOC的两个基本组件
- Context针对Bean和Core做了一些封装和扩展,能够让我们更加方便和高效的去实现IOC容器
- SpEL SpringEL表达式:获取容器或者配置中的数据
- AOP:面向切面编程的支持,Aspects是AOP的实现
- Data Access/Integration:数据的访问与集成模块(对持久层的支持),可以在这里集成mybatis类库
- Web:对Web层的支持(SpringMVC)
# 基本开发步骤
- 导入Spring开发的基本包坐标,目前稳定版5.2.10
<dependencies>
<dependency>
<groupId>org.springframwork</groupId>
<artifactId>spring-context</arctifactId>
<version>5.0.5.RELEASE</version>
</dependency>
</dependencies>
- 编写Dao接口和实现类
package dao;
public interface UserDao {
public void save();
}
public class UserDaoImpl implements UserDao {
@Override
public void save() {
System.out.println("运行成功");
}
}
- 创建Spring核心配置文件,在类路径(resources)下创建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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDao" class="dao.impl.UserDaoImpl"></bean>
</beans>
- 使用Spring的API获得Bean实例
public class UserDaoDemo {
public static main(String[] args){
ApplicationContext a = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDao userDao = (UserDao) a.getBean("userDao");
userDao.save();
}
}
# Spring配置文件
- Spring配置文件,用于创建对象,并存储到Spring容器中
- 默认情况下它调用的是类中的无参构造函数,如果没有无参构造函数则不能创建成功
<!--autowire自动装配-->
<!--lazy-init初始化的bean延迟加载-->
<bean id="userDao"
name="dao daoImpl"
class="dao.impl.UserDaoImpl"
scope="singleton"
init-method="init"
destroy-method="destory"
autowire="byType"
factory-method="getInstance"
factory-bean="com.sylone.factory.userFactory"
lazy-init="true">
</bean>
# 基本配置
- id:Bean实例在Spring容器中的唯一标识
- name:定义别名,可定义多个,使用逗号(,)分号(;)空格( )分割
- class:Bean的全限定名称
# 作用范围
- singleton:默认值,单例的
- Bean的实例化个数:1个
- Bean的实例化时机:当Spring核心文件被加载时,实例化Bean实例
- Bean的生命周期:
- 对象创建:当应用加载,创建容器时,对象就被创建了
- 对象运行:只要容器在,对象一直活着
- 对象销毁:当应用卸载,销毁容器时,对象就被销毁了
- prototype:多例的
- Bean的实例化个数:多个
- Bean的实例化时机:当调用getBean()方法时实例化Bean实例
- 对象创建:当使用对象时,创建新的对象实例
- 对象运行:只要对象在使用中,就一直活着
- 对象销毁:当对象长时间不用时,被 Java 的垃圾回收器回收了
# 生命周期
- init-method:指定类中的初始化方法名称
- destroy-method:指定类中销毁方法名称
public class UserDaoImpl implements UserDao {
@Override
public void save() {
System.out.println("运行成功");
}
public void int(){
System.out.println("初始化方法……");
}
public void destory(){
System.out.println("销毁方法……");
}
}
//或者,不需要配置文件
public class UserDaoImpl implements UserDao,InitializingBean,DisposableBean {
@Override
public void save() {
System.out.println("运行成功");
}
//在属性设置之后
public void afterPropertiesSet() throws Exception{
System.out.println("初始化方法……");
}
public void destory() throws Exception{
System.out.println("销毁方法……");
}
}
# 实例化三种方式
将实例化后的对象存储到容器中,方便调用
- 默认使用无参构造来创建类对象,如果bean中没有默认无参构造,会创建失败,无参构造可以是private
<bean id="userDao" class="com.xxx.dao.impl.UserDaoImpl"/>
- 工厂静态方法实例化(并不是所有的对象都是通过构造方法创建的,如DriverManage.getConnection)
public class StaticFactory {
public static UserDao getUserDao(){
return new UserDaoImpl();
}
}
<bean id="userDao" class="factory.StaticFactory" factory-method="getUserDao"></bean>
- 工厂实例方法实例化
public class StaticFactory {
public UserDao getUserDao(){
return new UserDaoImpl();
}
}
<bean id="factory" class="factory.StaticFactory"></bean>
<bean id="userDao" factory-bean="factory" factory-method="getUserDao"></bean>
- 工厂实例方法实例化增强版:FactoryBean
- spring在使用getBean()调用获得该bean时,会自动调用该bean的getObject()方法
- 每个 Bean 都会对应一个 FactoryBean,如 SqlSessionFactory 对应 SqlSessionFactoryBean
- 当配置文件中bean标签的class属性配置的实现类是FactoryBean时,通过 getBean()方法返回的不是FactoryBean本身,而是调用FactoryBean#getObject()方法所返回的对象,相当于getObject()代理了getBean()方法
public class UserDaoFactoryBean implements FactoryBean<UserDao> {
//代替原始实例工厂中创建对象的方法
@Override
public UserDao getObject() throws Exception{
return new UserDaoImpl();
}
@Override
public Class<?> getObjectType(){
return UserDao.class;
}
@Override
public boolean isSingleton(){
return false; //多例的
}
}
<bean id="userDao" class="com.xxx.factory.UserDaoFactoryBean"></bean>
# 引入其他配置文件(分模块开发)
实际开发中,Spring的配置内容非常多,这就导致Spring配置很繁杂且体积很大,所以,可以将部分配置拆解到其他,减少主配置文件的量
<import resource="applicationContext-xxx.xml"/>
# Spring依赖注入
# 依赖注入方式
- set方法注入引用类型(推荐使用)
//在UserServiceImpl中添加setUserDao方法
public class UserServeImpl implements UserServe {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void user() {
userDao.save();
}
}
<!--name是set方法后面的名称 但是第一个字母要小写 ref是bean的Id-->
<bean id="userDao" class="dao.impl.UserDaoImpl"/>
<bean id="userService" class="service.impl.UserServeImpl" >
<property name="userDao" ref="userDao"></property>
<!--可以定义多个-->
<property name="orderDao" ref="orderDao"></property>
</bean>
- set方法注入普通数据类型
public class UserDaoImpl implements UserDao {
//通过spring 注入值
private int age;
private String username;
public void setAge(int age) {
this.age = age;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public void save() {
System.out.println(username+" ----"+age);
System.out.println("运行成功");
}
}
<bean id="userDao" class="dao.impl.UserDaoImpl" >
<property name="username" value="张三"></property>
<property name="age" value="22"></property>
</bean>
<!--或者 与形参名解耦合-->
<bean id="userDao" class="dao.impl.UserDaoImpl" >
<property type="java.lang.String" value="张三"></property>
<property type="int" value="22"></property>
</bean>
<!--或者 防止类型相同-->
<bean id="userDao" class="dao.impl.UserDaoImpl" >
<property index="0" value="张三"></property>
<property index="1" value="22"></property>
</bean>
- 构造方法注入引用类型
//创建有参构造(必须先定义无参构造)
public class UserServeImpl implements UserServe {
private UserDao userDao ;
public UserServeImpl(UserDao userDao) {
this.userDao = userDao;
}
public UserServeImpl() {
}
@Override
public void user() {
userDao.save();
}
}
<bean id="userDao" class="dao.impl.UserDaoImpl"/>
<bean id="userService" class="service.impl.UserServeImpl" >
<!--构造方法注入 userDao是形参的名-->
<constructor-arg name="userDao" ref="userDao"></constructor-arg>
<!--可以定义多个-->
<constructor-arg name="orderDao" ref="orderDao"></constructor-arg>
</bean>
- 构造方法注入普通数据类型
//创建有参构造(必须先定义无参构造)
public class UserServeImpl implements UserServe {
private String name ;
private int size ;
public UserServeImpl(String name,int size) {
this.name = name;
this.size = size;
}
public UserServeImpl() {
}
@Override
public void user() {
userDao.save();
}
}
<bean id="userService" class="service.impl.UserServeImpl" >
<constructor-arg index="0" value="mysq1"/>
<constructor-arg index="1" value="10"/>
</bean>
# 自动装配
IoC容器根据bean所依赖的资源在容器中自动查找并注入到bean中的过程成为自动装配
- 按类型:byType (常用)
- 按名称:byName
- 按构造方法:constructor
- 不使用:no
public class UserServeImpl implements UserServe {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void user() {
userDao.save();
}
}
<bean id="userDao" class="dao.impl.UserDaoImpl"/>
<bean id="userService" class="service.impl.UserServeImpl" autoWire="byType"/>
<!--如果存在多个dao.impl.UserDaoImpl类型时-->
<bean id="userService" class="service.impl.UserServeImpl" autoWire="byName"/>
注意
- 自动装配用于引用类型依赖注入,不能对简单类型进行操作
- 自动装配的优先级低于set和构造方法注入,同时出现时自动装配失效
# 注入集合数据类型
public class User {
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
public class UserDaoImpl implements UserDao {
//通过spring 注入值
private List<String> stringList;
private Map<String, User> userMap;
private Properties properties;
public void setStringList(List<String> stringList) {
this.stringList = stringList;
}
public void setUserMap(Map<String, User> userMap) {
this.userMap = userMap;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
@Override
public void save() {
System.out.println(stringList+" ----");
System.out.println(userMap+" ----");
System.out.println(properties+" ----");
System.out.println("运行成功");
}
}
<!--数组类型-->
<bean id="userDao" class="dao.impl.UserDaoImpl" >
<property name="array">
<array>
<value>aaa</value>
<value>bb</value>
<value>acc</value>
</array>
</property>
</bean>
<!--List<String>类型-->
<bean id="userDao" class="dao.impl.UserDaoImpl" >
<property name="stringList">
<list>
<value>aaa</value>
<value>bb</value>
<value>acc</value>
</list>
</property>
</bean>
<!--List<User>类型-->
<!--首先给user注入值-->
<bean id="user1" class="domain.User">
<property name="name" value="sylone"></property>
<property name="age" value="11"></property>
</bean>
<bean id="user2" class="domain.User">
<property name="name" value="sylone"></property>
<property name="age" value="131"></property>
</bean>
<property name="userList">
<list>
<ref bean="user1"></ref>
<ref bean="user2"></ref>
</list>
</property>
<!--Set类型-->
<bean id="userDao" class="dao.impl.UserDaoImpl" >
<property name="userSet">
<set>
<value>aaa</value>
<value>bb</value>
<value>acc</value>
</set>
</property>
</bean>
<!--Map<String,User>类型-->
<bean id="userDao" class="dao.impl.UserDaoImpl" >
<property name="userMap">
<map>
<entry key="user1" value="zhangsan"></entry>
<entry key="user1" value-ref="user1"></entry>
<entry key="user2" value-ref="user2"></entry>
</map>
</property>
</bean>
<!--Properties类型-->
<bean id="userDao" class="dao.impl.UserDaoImpl" >
<property name="properties">
<props>
<prop key="p1">ppp1</prop>
<prop key="p2">ppp2</prop>
<prop key="p3">ppp3</prop>
</props>
</property>
</bean>
# Spring容器接口
- BeanFactory 是所有容器的顶层接口,通过BeanFactory获得的bean均为延迟加载
- ApplicationContext 是Spring容器的核心接口,初始化时bean立即被加载
# ApplicationContext
接口类型,代表应用上下文,可以通过其实例获得Spring容器中的Bean对象
ApplicationContext的实现类:
ClassPathXmlApplicationContext //它是从类的根路径下加载配置文件,推荐使用这种
FileSystemXmlApplicationContext //它是从磁盘路径上加载配置文件,配置文件可以在磁盘的任意位置
AnnotationConfigApplicationContext //当使用注解配置容器对象时,需要使用此类来创建 spring 容器
# getBean()
//多个文件时new ClassPathXmlApplicationContext("xml文件1,xml文件2");
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("xml文件");
UserService userService1 = (UserService)applicationContext.getBean("userService");
//根据类型获取
UserService userService2 = applicationContext.getBean(UserService.class);
注意
当参数的数据类型是字符串时,根据Bean的id从容器中获得Bean实例,返回是Object,需要强转
当参数的数据类型是Class类型时,表根据类型从容器中获得Bean实例,不需要强转,当容器中相同类型的Bean有多个时,则此方法会报错
# Spring注解开发
注解代替xml配置文件可以简化配置,提高开发效率
# 原始注解
//@Component("userDao")
//@Component 不添加名称获取bean时需要使用class方式(getBean(UserService.class))
@Repository("userDao")
public class UserDaoImpl implements UserDao {
public void save() {
System.out.println("save running...");
}
}
//@Component("userService")
@Service("userService")
//@Scope("prototype")
@Scope("singleton")
public class UserServiceImpl implements UserService {
@Value("${jdbc.driver}")
private String driver;
//<property name="userDao" ref="userDao"></property>
//@Autowired //可以单独配置,按照类型userDao从Spring容器中进行匹配
//@Qualifier("userDao") //按照名称从容器中进行匹配的 但是需要结合@Autowired一起使用
@Resource(name = "userDao") //@Resource 相当于 @Autowired+@Qualifier
private UserDao userDao;
//可以不用set
//public void setUserDao(UserDao userDao) {
// this.userDao = userDao;
//}
public void save() {
System.out.println(driver);
userDao.save();
}
@PostConstruct
public void init(){
System.out.println("Service对象初始化方法");
}
@PreDestroy
public void destroy(){
System.out.println("Service对象销毁方法");
}
}
@PostConstruct、@PreDestroy报红
在pom.xml中加上下面这段代码或者添加javax.annotation的jar包就可以了
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>jsr250-api</artifactId>
<version>1.0</version>
</dependency>
# 新注解
使用上面的注解还不能全部替代xml配置文件,还需要使用注解替代的配置如下:
- 非自定义的Bean的配置:bean
- 加载properties文件的配置:context:property-placeholder location=""
- 组件扫描的配置:context:component-scan base-package=""
- 引入其他文件:import resource=""
//SpringConfiguration.java
@Configuration //标志该类是Spring的核心配置类
@ComponentScan("com.lzjtu") //多个包@ComponentScan({"com.lzjtu","com.sylone"})
@Import({DataSourceConfiguration.class})
public class SpringConfiguration {
}
//DataSourceConfiguration.java
//<context:property-placeholder location='xx.properties'>
//路径仅支持单一文件配置,多文件请使用数组格式配置,不允许使用通配符*
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfiguration {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
//Spring会将当前方法的返回值以指定名称存储到Spring容器中
//getDataSource(UserService userService)中的形参可以是容器中的任意bean
@Bean("dataSource")
public DataSource getDataSource() throws Exception{
ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass(driver);
dataSource.setJdbcUrl(url);
dataSource.setUser(username);
dataSource.setPassword(password);
return dataSource;
}
}
测试加载核心配置类创建 Spring 容器
//ClassPathXmlApplicationContext app = new ClassPathXmlApplicationContext("xml文件");
ApplicationContext app = new AnnotationConfigApplicationContext(SpringConfiguration.class);
UserService userService = app.getBean(UserService.class);
userService.save();
DataSource ds = (DataSource) app.getBean("dataSource");
Connection connection = ds.getConnection();
System.out.println(connection);
connection.close();
//app.close();
# @Configuration注解
//proxyBeanMethods = true 可以保障调用此方法得到的对象是从容器中获取的不是新创建的
@Configuration(proxyBeanMethods = true) //默认值是true
@Configuration
public class RabbitConfigDirect {
@Bean
public Queue directQueue(){
//尽管是new对象,但是还是从容器中取得已有对象
return new Queue("dirct_queue");
}
@Bean
public DirectExchange directExchange(){
//尽管是new对象,但是还是从容器中取得已有对象
return new DirectExchange("directExchange");
}
@Bean
public Binding bindingDirect(){
return BindingBuilder
//调用容器中的已有对象
.bind(directQueue())
//调用容器中的已有对象
.to(directExchange())
.with("direct");
}
}
# @ComponentScan注解
一般和@Configuration注解一起使用,主要的作用就是定义包扫描的规则,然后根据定义的规则找出哪些需类需要自动装配到spring的bean容器中,然后交由spring进行统一管理
//包含Animal.class类可以被扫描到,包括其子类
@ComponentScan(value = "com.spring",
//是否开启可以对加@Component/@Repository/@Service/@Controller注解的类进行检测
//系统默认为true,需要手动设置false
useDefaultFilters = false,
//包含规则
includeFilters = {@Filter(type = FilterType.ASSIGNABLE_TYPE,
classes = {Animal.class})})
//排除包含@Controller注解的类
@ComponentScan(value = "com.spring",
//排除规则
excludeFilters = {@Filter(type = FilterType.ANNOTATION,
classes = {Controller.class}),})
//FilterType属性:
FilterType.ANNOTATION //按照注解过滤
FilterType.ASSIGNABLE_TYPE //按照给定的类型,指定具体的类,子类也会被扫描到
FilterType.ASPECTJ //使用ASPECTJ表达式
FilterType.REGEX //正则
FilterType.CUSTOM //自定义规则
# @Import与@ImportResource注解
- @Import来导入配置类或者导入一个带有@Component等注解要放入Spring容器中的类
- @ImportResource用来导入一个传统的xml配置文件,导入后可以将xml文件中的bean加载到容器中
@Configuration
@ComponentScan("com.spring")
@ImportResource("applicationContext-config.xml")
public class SpringConfig{
}
注意
声明的bean需要被扫描或者Import导入容器
# XML配置方式和注解配置的对比
# Spring集成Junit
- 让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它
- 将需要进行测试Bean直接在测试类中进行注入
# 集成Junit步骤
- 导入spring集成Junit的坐标
<!--此处需要注意的是,spring5 及以上版本要求 junit 的版本必须是 4.12 及以上-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
- 使用@Runwith注解替换原来的运行器
@RunWith(SpringJUnit4ClassRunner.class)
public class SpringJunitTest {
}
- 使用@ContextConfiguration指定配置文件或配置类
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
}
- 使用@Autowired注入需要测试的对象
@Autowired
private UserService userService;
- 创建测试方法进行测试
@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration("classpath:applicationContext.xml")
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
@Autowired
private UserService userService;
@Autowired
private DataSource dataSource;
@Test
public void test1() throws SQLException {
userService.save();
System.out.println(dataSource.getConnection());
}
}
# Spring集成Jdbc
Jdbc Template 是 spring 框架中提供的一个对象,是对原始繁琐的Jdbc API对象的简单封装
spring 框架为我们提供了很多的操作模板类。例如:操作关系型数据的JdbcTemplate,操作nosql数据库的RedisTemplate,操作消息队列的 JmsTemplate 等等
# JdbcTemplate开发步骤
- 导入数据库驱动坐标、数据源的坐标、spring-jdbc(spring操作与数据库相关的都要导此包)、spring-tx坐标
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.3.1</version>
</dependency>
- 创建数据库表和实体
public class Account {
private String name;
private double money;
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{" +
"name='" + name + '\'' +
", money=" + money +
'}';
}
}
- 数据库配置jdbc.properties(spring2.5以下版本需要添加serverTimezone)
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
jdbc.username=root //不能设置为username,防止于系统属性重复
jdbc.password=root
- 将DataSource的创建权交由Spring容器去完成
- DataSource有无参构造方法,而Spring默认就是通过无参构造方法实例化对象的
- DataSource要通过set方法设置数据库连接信息,而Spring可以通过set方法进行字符串注入
<?xml version="1.0" encoding="UTF-8"?>
<!--首先需要引入 context 命名空间和约束路径,需要替换5个地方-->
<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"
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">
<!--加载外部的properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--加载多个外部的properties文件-->
<context:property-placeholder location="classpath:jdbc1.properties,jdbc2.properties"/>
<context:property-placeholder location="classpath:*.properties"/>
<!--加载其他jar包中的多个外部的properties文件-->
<context:property-placeholder location="classpath*:*.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!--jdbc模版对象-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
或者使用java代码代替配置文件
//SpringConfig.java
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
@Configuration //相当于spring xml配置文件中的总体标签 <beans></beans>
@ComponentScan("com.itheima") //扫描该包下是否有注解bean的类
@PropertySource({"jdbc.properties"}) //配置加载jdbc.properties文件 使用$符获取数据
@Import({JdbcConfig.class}) //导入配置
public class SpringConfig {
}
//JdbcConfig.java
package com.itheima.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import javax.sql.DataSource;
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource(){
// 1、new 第三方bean/对象
DruidDataSource dataSource =new DruidDataSource();
// 2、给第三方bean/对象属性赋值
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
// 3、把第三方bean/对象返回给该方法
return dataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(){
return new JdbcTemplate(dataSource());
}
}
- JdbcTemplate的常用操作
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class JdbcTemplateCURDTest {
@Autowired
private JdbcTemplate jdbcTemplate;
@Test
public void testQueryCount(){
String sql = "select count(*) from account";
Long count = jdbcTemplate.queryForObject(sql, Long.class);
System.out.println(count);
}
@Test
public void testQueryOne(){
String sql = "select * from account where name=?";
Account account = jdbcTemplate.queryForObject(sql,
new BeanPropertyRowMapper<Account>(Account.class), "lisi");
System.out.println(account);
}
@Test
public void testQueryAll(){
String sql = "select * from account";
List<Account> accountList = jdbcTemplate.query(sql,
new BeanPropertyRowMapper<Account>(Account.class));
System.out.println(accountList);
}
@Test
public void testUpate(){
int row = jdbcTemplate.update("update account set money=? where name=?",100,"tom");
System.out.println(row);
}
@Test
public void testDelete(){
int row = jdbcTemplate.update("delete from account where name=?","tom");
System.out.println(row);
}
}
注意 解决错误信息:discard long time none received connection
- 启动时增加参数
-Ddruid.mysql.usePingMethod=false
- Spring Boot启动类增加以下代码
static {
System.setProperty("druid.mysql.usePingMethod","false");
}
- 自定义DruidConfig配置类增加
@PostConstruct
public void setProperties(){
System.setProperty("druid.mysql.usePingMethod","false");
}
# Spring切面编程
- AOP面向切面编程,是面向对象编程(OOP)的一种补充
- AOP可以在不修改源代码的情况下对方法进行功能增强
- 降低耦合度,提高程序的重用性,同时提高开发效率
# 底层实现
- AOP的底层原理是动态代理,通过Spring对代理对象进行功能增强,getBean返回的是其代理对象
- Spring框架会根据目标类是否实现了接口来决定使用哪种动态代理的方式(JDK代理、cglib代理)
# 相关概念
- Joinpoint:连接点,是指那些被拦截的方法(所有公民都有被选举权)
- Pointcut:切入点,是指我们要对哪些连接点方法进行拦截,连接点范围大于切入点(被选中的公民)
- Advice:通知/增强,拦截到切入点后要做的事情就是通知
- Aspect:切面,就是切入点 + 通知
- Weaving:织入,切入点和通知的结合的过程
# 切面表达式
用于描述要进行增强的方法,既可以是接口方法,也可以是接口的实现类方法,一般是接口方法
//描述方式一:执行com.sylone.aop包下的Target接口中的无参数method方法
execution(public void com.sylone.aop.Target.method())
//描述方式一:执行com.sylone.aop包下的TargetImpl了类中的无参数method方法
execution(public void com.sylone.aop.TargetImpl.method())
标准格式:
execution([修饰符] 返回值类型 包名.类名.方法名(参数) 异常名)
- 访问修饰符可以省略
- 返回值类型、包名、类名、方法名可以使用星号*代表任意
- 包名与类名之间一个点. 代表当前包下的类,两个点..表示当前包及其子包下的类,尽量不适用,效率低
- 参数列表可以使用两个点.. 表示任意个数,任意类型的参数列表,一个* 代表必带一个任意参数
execution(public void com.sylone.aop.Target.method(*))
execution(void com.sylone.aop.Target.*(..))
execution(void com.sylone.aop.Target.method*(..)) //方法以method开头的
execution(* com.sylone.aop.*.*(..))
execution(* com.sylone.aop..*.*(..))
execution(* *..*.*(..))
# 通知的类型
- 前置通知(aop:before):指定增强的方法在切入点方法之前执行
- 后置通知(aop:after-returning):指定增强的方法在切入点方法之后执行,有异常不会执行
- 环绕通知(aop:around):指定增强的方法在切入点方法之前和之后都执行
- 异常抛出通知(aop:throwing):指定增强的方法在出现异常时执行
- 最终通知(aop:after):用于配置最终通知。无论增强方式执行是否有异常都会执行
public class MyAspect {
@Before("execution(* com.sylone.aop.innovation.*.*(..))")
public void before(JoinPoint jp){
Obiect[] args = jp.getArgs();//获取所有的参数
System.out.println(Arrays.toString(args));//字符串的形式输出数组
System.out.println("对核心业务方法执行前的增强......");
}
@AfterReturning("execution(* com.sylone.aop.innovation.*.*(..))")
public void afterReturning(JoinPoint jp){
Obiect[] args = jp.getArgs();//获取所有的参数
System.out.println(Arrays.toString(args));//字符串的形式输出数组
System.out.println("后置增强......");
}
//接收原始方法的返回值return = "obj"
@AfterReturning(value = "execution(* com.sylone.aop.innovation.*.*(..))",return = "obj")
public void afterReturning(JoinPoint jp,Object obj){//JoinPoint必须在前面
System.out.println("后置增强......"+ obj);
}
//ProceedingJoinPoint:正在执行的连接点=>切点
//如果原始方法有返回值,返回值类型为Object,然后return返回值
//如果原始方法没有返回值为void,返回值类型为Object时return的值为null
public Object around(ProceedingJoinPoint pjp) throws Throwable {
System.out.pringIn("环绕前执行……")
Signature signature = pjp.getSignature();//一次执行的签名信息
signature.getName();//获取方法名
signature.getDeclaringTypeName();//获取带包的方法名
Obiect[] args = pjp.getArgs();//获取所有的参数
System.out.println(Arrays.toString(args));//字符串的形式输出数组
Object proceed = pjp.proceed(args);//传递args和不传一样,在此处可以修改参数的值
Object proceed = pjp.proceed();
System.out.pringIn("环绕后执行……")
return proceed;
}
@After("execution(* com.sylone.aop.innovation.*.*(..))")
public void after(JoinPoint jp){
Obiect[] args = jp.getArgs();//获取所有的参数
System.out.println(Arrays.toString(args));//字符串的形式输出数组
System.out.println("后置增强......");
}
@Throwing("execution(* com.sylone.aop.innovation.*.*(..))")
public void throwing(JoinPoint jp){
Obiect[] args = jp.getArgs();//获取所有的参数
System.out.println(Arrays.toString(args));//字符串的形式输出数组
System.out.println("后置增强......");
}
//接收异常信息
@Throwing(value = "execution(* com.sylone.aop.innovation.*.*(..))",throwing = "t")
public void throwing(JoinPoint jp,Throwable t){
System.out.println("后置增强......"+t);
}
}
# 基于XML的AOP
- 导入AOP依赖包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
- 创建目标类和接口
public interface TargetInterface {
public void work();
}
public class Target implements TargetInterface {
@Override
public void work() {
System.out.println("===核心业务方法运行===");
}
}
- 创建切面类(增强方法类)
public class Aspect {
public void before(){
System.out.println("对核心业务方法执行前的增强......");
}
public void after(){
System.out.println("后置增强......");
}
}
- 将目标类和切面类交给Spring管理
<!-- 目标对象 -->
<bean id="target" class="com.aop.Target"></bean>
<!-- 切面对象 -->
<bean id="aspect" class="com.aop.Aspect"></bean>
- 在核心配置文件中配置织入关系
<!--导入约束-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--配置AOP-->
<aop:config>
<aop:aspect ref="aspect">
<aop:before method="before" pointcut="execution(public void com.aop.Target.work())"/>
<aop:after method="after" pointcut="execution(public void com.aop.Target.work())"/>
</aop:aspect>
</aop:config>
- 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {
@Autowired
private TargetInterface target;
@Test
public void test() {
target.coreWork();
}
}
# 切点表达式的抽取
<aop:config>
<aop:pointcut id="pointCut" expression="execution(public void com.aop.Target.work())"/>
<aop:aspect ref="tAspect">
<!--returning增强方法的参数名,用来接收执行目标方法后获得的返回值-->
<aop:after-returning method="log" pointcut-ref="pointCut" returning="isSucccess"/>
</aop:aspect>
</aop:config>
# 基于注解的AOP
- 导入AOP依赖包
- 创建目标接口和目标类(内部有切点)
public interface TargetInterface {
public void coreWork();
}
@Componet("Target")
public class Target implements TargetInterface {
@Override
public void coreWork() {
System.out.println("===核心业务方法运行===");
}
}
- 创建切面类(增强方法类),将目标类和切面类的对象创建权交给spring并使用注解配置织入关系
@Component("aspect")
@Aspect
public class MyAspect {
@Before("execution(* com.sylone.aop.innovation.*.*(..))")
public void before(){
System.out.println("对核心业务方法执行前的增强......");
}
@After("execution(* com.sylone.aop.innovation.*.*(..))")
public void after(){
System.out.println("后置增强......");
}
@Around("execution(* com.sylone.aop.innovation.*.*(..))")
public Object around(ProceedingJoinPoint pjp) throws Throwable{
System.out.println("环绕前增强......");
Object proceed = pjp.proceed();
System.out.println("环绕后增强......");
return proceed;
}
}
- 在配置文件中开启组件扫描和AOP 的自动代理
<!--导入约束,组件扫描,增加context命名空间-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.sylone.aop.innovation"/>
<!--aop的自动代理-->
<aop:aspectj-autoproxy/>
或者使用SpringConfig.java
@Configuration
@ComponentScan("com.sylone.aop")
@EnableAspectJAutoProxy //代替<aop:aspectj-autoproxy/>
public class SpringConfig{
}
- 测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class AopTest {
@Autowired
private TargetInterface target;
@Test
public void test() {
target.coreWork();
}
}
# 切点表达式的抽取
抽取的方式是在切面内定义私有方法,再使用@Pointcut注解定义切点表达式,然后在增强注解中引用
@Component("aspect")
@Aspect
public class MyAspect {
@Pointcut("execution(* com.sylone.aop.innovation.*.*(..))")
private void myPoint(){}
//或者 @Before("myPoint()")
@Before("MyAspect.myPoint()")
public void before(){
System.out.println("对核心业务方法执行前的增强......");
}
}
# Spring事务控制
# 编程式事务控制相关对象
- PlatformTransactionManager:事务的管理对象,控制事务的行为,提供了我们常用的操作事物的方法
TransactionStatus getTransaction(TransactionDefination defination) //获取事务的状态信息
void commit(TransactionStatus status) //提交事务
void rollback(TransactionStatus status) //回滚事务
//PlatformTransactionManager 是接口类型,不同的Dao层技术有不同的实现类
//例如:Dao层技术是Jdbc或mybatis时
org.springframework.jdbc.datasource.DatasourceTransactionManager
//Dao层是hibernate时
org.springframework.orm.hibernate5.hiberTransactionManager
- TransactionDefination:事务的定义对象,设置事务的参数信息,有如下方法
//设置隔离级别,可以解决事物并产生的问题,如脏读、不可重复读和虚读。
//ISOLATION_DEFAULT
//JSOLATION_READ_UNCOMMITTED
//ISOLATION_READ_COMMITTED
//JSOLATION_REPEATABLE_READ
//ISOLATION_SERIALTZABLE
int getIsolationLevel() //获取事务的隔离级别
//事务的传播行为
//required:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。默认值
//requires_new:无论当前有无事务,都会新建一个事务
//supports:如果当前有事务,就加入到这个事务中,如果当前没有事务则不开启事务
//not_supported:无论当前有无事务,都不开启事务
//mandatory:如果当前没有事务,就抛出异常
//never:如果当前存在事务,抛出异常
//nested:事务回滚到指定的回滚点
int getPropagationBehavior() //获取事务的传播行为
int getTimeout() //获得超时时间,默认值为-1,没有超时时间。有,就以秒为单位
boolean isReadonly() //是否只读,建议查询设置为只读
- TransactionStatus:事务的状态对象,接口提供的是事务具体的运行状态
boolean hasSavepoint() //是否存储回滚点
boolean isCompleted() //事务是否完成
boolean isNewTransaction() //是否是新事务
boolean isRollbackOnly() //事务是否回滚
注意
在xml和注解配置事务控制时
PlatformTransactionManager需要指定Dao层使用的技术
TransactionDefination需要配置
TransactionStatus不需要配置,它是被动的
# 事务的角色
如果事务不需要加入已有事务时,需要requires_new
- 事务管理员:发起事务方在Spring中通常指代业务层开启事务的方法
- 事务协调员:加入事务方在Spring中通常指代数据层方法,也可以是业务层方法
# 基于XML的声明式事务控制
采用配置文件的方式来处理事务,Spring声明事务控制底层就是AOP
- 创建maven工程,并导入坐标
<dependencies>
<!--Spring核心容器-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.19.RELEASE</version>
</dependency>
<!--SpringJdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.19.RELEASE</version>
</dependency>
<!--事务相关的-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.19.RELEASE</version>
</dependency>
<!--SpringAOP相关的坐标-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<!--数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--连接池-->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.1.0</version>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
</dependencies>
- 业务逻辑
//数据库表
create table account(
id int primary key auto_increment,
name varchar(40),
money double
)character set utf8 collate utf8_general_ci;
insert into account(name,money) values('zs',1000);
insert into account(name,money) values('ls',1000);
insert into account(name,money) values('ww',1000);
//实体类
@Data
public class Account implements Serializable {
private Integer id;
private String name;
private Double money;
}
//配置数据源和JdbcTemplate
@Configuration
public class Config {
@Bean
public DataSource dataSource(){
HikariDataSource hikariDataSource = new HikariDataSource();
hikariDataSource.setDriverClassName("com.mysql.jdbc.Driver");
hikariDataSource.setJdbcUrl("jdbc:mysql://localhost:3307/spring_learning");
hikariDataSource.setUsername("root");
hikariDataSource.setPassword("123456");
return hikariDataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
}
//业务类
public interface AccountService {
void transAccount(Integer beTransId,Integer transId,Double money);
List<Account> queryAll();
}
//实现类
@Service
public class AccountServiceImpl implements AccountService {
@Autowired
AccountDao accountDao;
@Autowired
DataSource dataSource;
@Autowired
JdbcTemplate jdbcTemplate;
public void transAccount(Integer beTransId, Integer transId,Double money){
//1.将zs账户中的前减100
accountDao.transAccount(beTransId,AccountDao.REDUCE,money);
//2.给ls账户加100
accountDao.transAccount(transId,AccountDao.ADD,money);
}
@Override
public List<Account> queryAll() {
String sql = "select * from account";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Account.class));
}
}
//数据访问层
@Repository
public class AccountDao {
@Autowired
JdbcTemplate jdbcTemplate;
public static Integer REDUCE = 0;
public static Integer ADD = 1;
public int transAccount(Integer userId, Integer beh, Double money) {
String sql = "";
if(beh==ADD){
sql = "update account set money=money+? where id=?";
}else if(beh==REDUCE){
sql = "update account set money=money-? where id=?";
}else{
throw new RuntimeException("beh只能是0或1");
}
return jdbcTemplate.update(sql,money,userId);
}
}
- 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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.itmentu"/>
<!-- 目标对象 内部的方法就是切点-->
<bean id="accountService" class="com.itmentu.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao"/>
</bean>
<!--事务的管理对象-->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--通知 事务的增强-->
<tx:advice id="adviceId" transaction-manager="transactionManager">
<!--在tx:advice标签内部 配置事务的属性 -->
<tx:attributes>
<!--代表切点方法的事务参数的配置-->
<tx:method name="*" read-only="false" propagation="REQUIRED"/>
<!--query开头的方法指定为只读,以非事务方式执行-->
<tx:method name="query*" read-only="true" propagation="SUPPORTS"/>
</tx:attributes>
</tx:advice>
<!--配置事务织入-->
<aop:config>
<!-- 定义切入点 ,也就是到底给那些类中的那些方法加入事务的管理 -->
<aop:pointcut id="pointCat"
expression="execution(* com.itmentu.service.impl.*.*(..))"/>
<!-- 让切入点和事务的建议绑定到一起 -->
<aop:advisor advice-ref="adviceId" pointcut-ref="pointCat"/>
<!-- 或者使用下面的方式-->
<aop:advisor advice-ref="adviceId"
pointcut="execution(* com.zking.service.*.*(..))"/>
</aop:config>
</beans>
# 基于注解的声明式事务控制
- 在需要使用事务的方法或者类上面加@Transactional注解,对应TransactionDefination事务的定义对象
- Spring注解式事务通常添加在业务层接口中而不会添加到业务层实现类中,降低耦合
- 注解式事务可以添加到业务方法上表示当前方法开启事务,也可以添加到接口上表示当前接口所有方法开启事务
//实现类
@Service
@Transactional(propagation = "REQUIRED",//REQUIRES_NEW 设置新事务
readonly = true,
timeout = 1,
//有些异常是不参与回滚的,只有 ERROR 异常和运行异常 RuntimeException 才会回滚
//想针对某些异常进行事务回滚,使用 rollbackFor 属性明确指定异常
rollbackFor = {IOException.class})
public class AccountServiceImpl implements AccountService {
@Autowired
AccountDao accountDao;
@Autowired
DataSource dataSource;
@Autowired
JdbcTemplate jdbcTemplate;
@Transactional(propagation = "REQUIRED")
public void transAccount(Integer beTransId, Integer transId,Double money){
//1.将zs账户中的前减100
accountDao.transAccount(beTransId,AccountDao.REDUCE,money);
//2.给ls账户加100
accountDao.transAccount(transId,AccountDao.ADD,money);
}
@Override
public List<Account> queryAll() {
String sql = "select * from account";
return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Account.class));
}
}
- 在业务层手工捕捉并处理了异常,把异常"吃"掉了,Spring自然不知道这里有错,更不会主动去回滚数据,推荐做法:在业务层统一抛出异常,然后在控制层统一处理
@Transactional
public int insertUser(User user) throws Exception
{
// 新增用户信息
int rows = userMapper.insertUser(user);
// 新增用户岗位关联
insertUserPost(user);
// 新增用户与角色管理
insertUserRole(user);
// 模拟抛出SQLException异常
boolean flag = true;
if (flag)
{
try
{
// 谨慎:尽量不要在业务层捕捉异常并处理
throw new SQLException("发生异常了..");
}
catch (Exception e)
{
e.printStackTrace();
}
}
return rows;
}
//推荐做法
@Transactional
public int insertUser(User user) throws Exception
{
// 新增用户信息
int rows = userMapper.insertUser(user);
// 新增用户岗位关联
insertUserPost(user);
// 新增用户与角色管理
insertUserRole(user);
// 模拟抛出SQLException异常
boolean flag = true;
if (flag)
{
throw new RuntimeException("发生异常了..");
}
return rows;
}
- 使用@EnableTransactionManagement注解开启事务
@Configuration
@EnableTransactionManagement
@ComponentScan("com.itmentu")
public class Config {
@Bean
public TransactionManager transactionManager(DataSource dataSource){
return new DataSourceTransactionManager(dataSource);
}
@Bean
public DataSource dataSource(){
HikariDataSource hikariDataSource = new HikariDataSource();
hikariDataSource.setDriverClassName("com.mysql.jdbc.Driver");
hikariDataSource.setJdbcUrl("jdbc:mysql://localhost:3307/spring_learning");
hikariDataSource.setUsername("root");
hikariDataSource.setPassword("123456");
return hikariDataSource;
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource){
return new JdbcTemplate(dataSource);
}
}
//或者在配置文件中配置
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager">
# Spring集成web
# ApplicationContext应用上下文获取方式
用上下文对象是通过 new ClasspathXmlApplicationContext(spring配置文件) 方式获取的,但是每次从容器中获得 Bean 时都要编写 new ClasspathXmlApplicationContext(spring配置文件) ,这样的弊端是配置文件加载多次,应用上下文对象创建多次。
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = (UserService) app.getBean("userService");
userService.save();
}
}
在 Web 项目中,可以使用 ServletContextListener 监听 Web 应用的启动,我们可以在 Web 应用启动时,就加载 Spring 的配置文件,创建应用上下文对象 ApplicationContext,在将其存储到最大的域 servletContext 域中,这样就可以在任意位置从域中获得应用上下文 ApplicationContext 对象了。
<!--在web.xml中配置核心配置文件的位置-->
<context-param>
<param-name>applicationContextLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>com.sylone.listener.ContextLoaderListener</listener-class>
</listener>
public class ContextLoaderListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
ServletContext sc = servletContextEvent.getServletContext();
// 读取web.xml中配置的Spring核心配置文件的位置
String appContextLocation = sc.getInitParameter("applicationContextLocation");
// 创建ApplicationContext上下文对象
ApplicationContext app = new ClassPathXmlApplicationContext(appContextLocation);
// 将ApplicationContext对象存到域中
sc.setAttribute("app",app);
System.out.println("创建ApplicationContext对象成功:" + app);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
}
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ApplicationContext app=(ApplicationContext)req.getServletContext().getAttribute("app");
UserService userService = (UserService)app.getBean("userService");
userService.save();
}
}
# Spring提供获取应用上下文的工具
Spring 提供了一个监听器 ContextLoaderListener 就是对上述功能的封装,该监听器内部加载 Spring 配置文件,创建应用上下文对象,并存储到 ServletContext 域中,还提供了一个客户端工具 WebApplicationContextUtils 供使用者获得应用上下文对象。
- 导入Spring集成web的坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.1</version>
</dependency>
- 配置ContextLoaderListener监听器
<!-- 全局参数 -->
<context-param>
<!-- name固定 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- 配置监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
- 通过工具获得应用上下文对象
@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
//ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml")
ServletContext sc = this.getServletContext();
ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(sc);
UserService userService = (UserService) app.getBean("userService");
userService.save();
}
}
# SpringMVC概述
SpringMVC 已经成为目前最主流的MVC框架之一,并且随着Spring3.0 的发布,全面超越 Struts2,成为最优秀的 MVC 框架。它通过一套注解,让一个简单的 Java 类成为处理请求的控制器,而无须实现任何接口。同时它还支持 RESTful 编程风格的请求。
# 执行流程
DispatcherServlet 启动时,会创建 Spring 应用上下文,并加载配置文件或配置类中所声明的 bean,因此我们需要在 DispatcherServlet 的配置中指定 bean 所在的配置文件或 java Configuration 类,这些 bean 包含 web 组件的 bean,如 Controller、视图解析器及处理器映射
- 用户发送请求至前端控制器DispatcherServlet
- DispatcherServlet收到请求调用HandlerMapping处理器映射器
- 处理器映射器找到具体的处理器(可以根据xml配置、注解进行查找),生成处理器对象及处理器拦截器一并返回给DispatcherServlet
- DispatcherServlet调用HandlerAdapter处理器适配器
- HandlerAdapter调用具体的处理器(Controller,也叫后端控制器),执行完成返回ModelAndView
- DispatcherServlet将ModelAndView传给ViewReslover视图解析器
- ViewReslover解析后返回具体View
- DispatcherServlet根据View进行渲染视图(即将模型数据填充至视图中)响应用户。
# XML配置解析
SpringMVC有默认组件配置,默认组件都是 DispatcherServlet.properties 配置文件中配置的
该配置文件地址 org/springframework/web/servlet/DispatcherServlet.properties
翻看该解析器源码,可以看到该解析器的默认设置,如下:
REDIRECT_URL_PREFIX = "redirect:"//重定向前缀
FORWARD_URL_PREFIX = "forward:"//转发前缀(默认值)
prefix = "";//视图名称前缀
suffix = "";//视图名称后缀
我们可以通过属性注入的方式修改视图的的前后缀
<!-- 配置内部资源视图解析器 -->
<bean id="viewResolve"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
# 快速入门
DispatcherServlet是SpringMVC的核心,担任着请求分发的责任。在SpringMVC中配置DispatcherServlet有两种方式:
# 在web.xml文件中配置DispatcherServlet
- 导入SpringMVC相关坐标
<!--导入Spring和SpringMVC的坐标-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.1</version>
</dependency>
<!--导入Servlet和Jsp的坐标-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
- 在web.xml配置SpringMVC的核心控制器
<!-- 配置Spring的前端控制器-->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- 加载SpringMVC配置文件-->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-mvc.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>
- 创建Controller和业务方法
@Controller
public class UserController {
@RequestMapping("/quick")
public String save(){
System.out.println("Controller save running...,");
return "success.jsp";
}
}
- 创建spring-mvc.xml(增加context)
<?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"
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">
<!--Controller的组件扫描,Service、Dao层的扫描还是由Spring的核心配置文件来完成-->
<context:component-scan base-package="com.lzjtu.controller" />
</beans>
- 创建applicationContext.xml(排除controller的扫描)
<?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"
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>
<!--组件扫描 扫描service和mapper-->
<context:component-scan base-package="com.lzjtu">
<!--排除controller的扫描-->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
</beans>
# 用Java代码配置DispatcherServlet
通过扩展AbstractAnnotationConfigDispatcherServletInitializer抽象类,可以将DispatcherServlet和Spring应用上下文配置到Servlet容器中。
- ServletContainerInitializer
在Servlet3.0中新增了一个接口:ServletContainerInitializer,Servlet容器会在类路径中寻找实现了该接口的类,然后用它来配置Servlet容器。 这个接口功能特别的牛逼,有了它之后,可以不要 web.xml 配置文件了。
- SpringServletContainerInitializer
幸运的是Spring已经为我们提供了这个接口的实现类,名为SpringServletContainerInitializer,在这个类中又会查找WebApplicationInitializer接口的实现类,然后将配置的任务交给这个接口的实现类来完成。
//类上有@HandlesTypes这个注解,注解的值为WebApplicationInitializer.class
//所以onStartup方法的第一个参数是WebApplicationInitializer类型的集合
//这个集合由web容器自动扫描获取,然后传入进来
//实例化 WebApplicationInitializer 集合
//对 WebApplicationInitializer 集合进行排序
//循环调用 WebApplicationInitializer 的 onStartup 方法
//HandlesTypes表示当前ServletContainerInitializer的实现类能处理的类型
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses
, ServletContext servletContext) throws ServletException {
List<WebApplicationInitializer> initializers = Collections.emptyList();
if (webAppInitializerClasses != null) {
initializers = new ArrayList<>(webAppInitializerClasses.size());
for (Class<?> waiClass : webAppInitializerClasses) {
// Be defensive: Some servlet containers provide us with invalid classes,
// no matter what @HandlesTypes says...
if(!waiClass.isInterface()&&!Modifier.isAbstract(waiClass.getModifiers()) &&
WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
try {
initializers.add((WebApplicationInitializer)
ReflectionUtils.accessibleConstructor(waiClass).newInstance());
}
catch (Throwable ex) {
String er = "Failed to instantiate WebApplicationInitializer class";
throw new ServletException(er, ex);
}
}
}
}
if (initializers.isEmpty()) {
String er = "No Spring WebApplicationInitializer types detected on classpath";
servletContext.log(er);
return;
}
String err = "Spring WebApplicationInitializers detected on classpath";
servletContext.log(initializers.size() + err);
AnnotationAwareOrderComparator.sort(initializers);
for (WebApplicationInitializer initializer : initializers) {
initializer.onStartup(servletContext);
}
}
}
- WebApplicationInitializer
web 应用初始化,接口比较简单,就一个方法,参数是 servlet 上下文对象,有了个对象,可以干 web.xml 中的一切事情了,比如注册 servlet、filter、监听器等等。
public interface WebApplicationInitializer {
void onStartup(ServletContext servletContext) throws ServletException;
}
- AbstractContextLoaderInitializer
创建 ContextLoaderListener 监听器,这是一个 ServletContextListener 类型的监听器,所以在 web 容器启动和销毁的过程中会被调用。
类的继承关系:
WebApplicationInitializer
AbstractContextLoaderInitializer
AbstractDispatcherServletInitializer
AbstractAnnotationConfigDispatcherServletInitializer
- AbstractDispatcherServletInitializer
//类名随便写,Servlet容器会在类路径中寻找实现javax.servlet.ServletContainerInitializer接口的类
public class DispatcherServletInitializer extends AbstractDispatcherServletInitializer {
//设置springmvc容器的spring配置类
@Override
protected WebApplicationContext createServletApplicationContext() {
AnnotationConfigWebApplicationContext app=new AnnotationConfigWebApplicationContext()
app.register(SpringMvcConfig.class);
return app;
}
//配置DispatcherServlet的url-pattern
@Override
protected String[] getServletMappings() {
// "/" 所有,但不包括.jsp/.html; "/*" 表示包括.jsp/.html 的所有
return new String[]{"/"};
}
// springmvc容器的父容器spring配置类
// 实际工作中我们的项目比较复杂,可以将controller层放在springmvc容器中
// 其他层,如service层、dao层放在父容器了,bean管理起来更清晰一些
// 也可以没有父容器,将所有bean都放在springmvc容器中
@Override
protected WebApplicationContext createRootApplicationContext() {
return null;
}
//添加过滤器,解决乱码问题
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("UTF-8");
characterEncodingFilter.setForceRequestEncoding(true);
characterEncodingFilter.setForceResponseEncoding(true);
return new Filter[]{characterEncodingFilter};
}
}
- AbstractAnnotationConfigDispatcherServletInitializer
AbstractAnnotationConfigDispatcherServletInitializer是Spring3.2中引入了WebApplicationInitializer接口的基础实现类(这是一个抽象类)。
//类名随便写,Servlet容器会在类路径中寻找实现javax.servlet.ServletContainerInitializer接口的类
public class DispatcherServletInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { RootConfig.class };
}
//指定配置类
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebConfig.class };
}
//将DispatcherServlet映射到“/”
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
//WebConfig 实现
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
/**
* 1、开启SpringMVC多项辅助功能
* 2、配置视图解析器
* 3、配置截器
* 4、配置静态资源访问
* 5、配置文件上传解析器
* 6、配置全局异常处理器
*/
@Configuration
// 可以开启json数据转对象的功能、根据类型匹配对应的类型转换器
@EnableWebMvc // 开启SpringMVC多项辅助功能
@ComponentScan("com.windcloud.config") // 启用组件扫描
public class WebConfig extends WebMvcConfigurerAdapter {
//添加视图解析器(可以添加多个)
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/view/");
resolver.setSuffix(".jsp");
resolver.setOrder(Ordered.LOWEST_PRECEDENCE);
registry.viewResolver(resolver);
}
//请求转发给/名为的视图index
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
}
//类型转换
@Override
public void addFormatters(FormatterRegistry registry) {
// ...
}
//验证规则
@Override
public Validator getValidator() {
return null;
}
//添加拦截器(可以添加多个)
@Autowired
private MyInterceptor myInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.myInterceptor).addPathPatterns("/**");
}
//配置静态资源访问处理器
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//当访问/pages/**时候,从/pages目录下查找内容
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
//使用默认的
configurer.enable();
}
@Override
public void addCorsMappings(CorsRegistry registry) {
// 设置允许跨域的路径
registry.addMapping("/**")
// 设置允许跨域请求的域名
.allowedOrigins("file.sdxsk.com:8080")
// 是否允许证书
.allowCredentials(true)
// 设置允许的方法
.allowedMethods("GET", "POST", "DELETE", "PUT")
// 设置允许的header属性
.allowedHeaders("*")
// 跨域允许时间
.maxAge(3600);
WebMvcConfigurer.super.addCorsMappings(registry);
}
//配置文件上传解析器
@Bean
public CommonsMultipartResolver multipartResolver() {
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
//maxUploadSizePerFile:单个文件大小限制(byte)
//maxUploadSize:整个请求大小限制(byte)
commonsMultipartResolver.setMaxUploadSizePerFile(10 * 1024 * 1024);
commonsMultipartResolver.setMaxUploadSize(100 * 1024 * 1024);
return commonsMultipartResolver;
}
}
配置拦截器
public class MyInterceptor implements HandlerInterceptor {
//目标方法运行之前执行
public boolean preHandle(HttpServletRequest req, HttpServletResponse res
, Object handler) throws Exception {
// TODO Auto-generated method stub
System.out.println("preHandle..." + request.getRequestURI());
return true;
}
//目标方法执行正确以后执行
public void postHandle(HttpServletRequest req, HttpServletResponse res
, Object handler, ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
System.out.println("postHandle...");
}
//页面响应以后执行
public void afterCompletion(HttpServletRequest req, HttpServletResponse res
, Object handler, Exception ex) throws Exception {
// TODO Auto-generated method stub
System.out.println("afterCompletion...");
}
}
//RootConfig 实现
package com.windcloud.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
//@ComponentScan({"com.itheima.service","com.itheima.dao"})
@ComponentScan(basePackages = { "com.itheima" },
excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION
, value = Controller.class)})
public class RootConfig {
}
# @RequestMapping
用于建立请求 URL 和处理请求方法之间的对应关系
- 放在类上:请求URL的第一级访问目录。此处不写的话,就相当于应用的根目录
- 放在方法上:请求URL的第二级访问目录,与类上的使用@ReqquestMapping的目录一起组成虚拟路径
- value:用于指定请求的URL。它和path属性的作用是一样的。整个项目中不能重复
- method:用于指定请求的方式(RequestMethod.GET、PUT、POST、DELETE、PATCH)
@RequestMapping(value = "/add",method ={RequestMethod.POST} )
- headers:发送的请求中必须包含的请求头
@RequestMapping(value = "/add",headers ="content-type=text/*" )
- params:用于指定请求参数的限制条件。它支持简单的表达式
- params = {"accountName"},表示请求参数必须有accountName
- params = {"moeny!=100"},表示请求参数中money不能是100
@RequestMapping(value = "/add",params = {"accountName","moeny!=100"})
# SpringMVC响应数据
# 页面跳转
# 直接返回字符串
此种方式会将返回的字符串与视图解析器的前后缀拼接后跳转
@RequestMapping(value="/test", method= RequestMethod.GET, params = {"username"})
public String test(){
//return "/test.jsp";
//return "forward:/test.jsp";(默认是此种方式)
//return "redirect:/test.jsp";
return "test";
}
# 返回ModelAndView对象
- 原始方式
@RequestMapping(value="/test2")
public ModelAndView test2(){
ModelAndView modelAndView = new ModelAndView();
// 设置模型数据,在test.jsp中可通过${username}获取
modelAndView.addObject("username", "wxx");
// 设置视图名称
modelAndView.setViewName("test");
return modelAndView;
}
- 通过SpringMVC框架注入参数
//注入ModelAndView
@RequestMapping(value="/test3")
public ModelAndView test3(ModelAndView modelAndView){
modelAndView.addObject("username", "hxx");
modelAndView.setViewName("test");
return modelAndView;
}
//注入Model
@RequestMapping(value="/test3")
public String test3(Model model){
model.addAttribute("username", "hxx");
return "index";
}
//注入ModelMap
@RequestMapping(value="/test3")
public String test3(ModelMap model){
model.addAttribute("username", "hxx");
return "index";
}
//注入request
@RequestMapping(value="/test5")
public String test5(HttpServletRequest request){
//获取当前访问地址的url
String url = request.getScheme() + "://"
+ request.getServerName() + ":"
+ request.getServerPort()
+ request.getContextPath()
+ request.getServletPath();
return "test";
}
默认情况下Spring MVC将模型中的数据存储到request域中。当一个请求结束后,数据就失效了。如果要跨页面使用。那么需要使用到session。而@SessionAttributes注解就可以使得模型中的数据存储一份到session域中。
- @SessionAttributes只能定义在Class,interface enum上,作用是将指定的Model中的键值对添加至session中,方便在一个会话中使用
- @ModelAttribute可以将ModelMap中的属性绑定到请求处理方法的入参中
@Controller
@RequestMapping("/bbtForum.do")
@SessionAttributes("currUser") //①让ModelMap的currUser属性拥有session级作用域
public class BbtForumController {
@Autowired
private BbtForumService bbtForumService;
@RequestMapping(params = "method=listBoardTopic")
public String listBoardTopic(@RequestParam("id")int topicId, User user,ModelMap model) {
bbtForumService.getBoardTopics(topicId);
System.out.println("topicId:" + topicId);
System.out.println("user:" + user);
model.addAttribute("currUser",user); //向ModelMap中添加一个属性
return "listTopic";
}
@RequestMapping(params = "method=listAllBoard")
//③将ModelMap中的currUser属性绑定到user入参中
public String listAllBoard(@ModelAttribute("currUser") User user) {
bbtForumService.getAllBoard();
System.out.println("user:"+user);
return "listBoard";
}
}
# 回写数据
# 回写字符串
- 通过SpringMVC框架注入的response对象
@RequestMapping(value="/test6")
public void test6(HttpServletResponse response) throws IOException {
response.getWriter().println("Hello World!");
}
- 通过@ResponseBody注解告知SpringMVC框架不进行视图跳转,直接进行数据响应
@RequestMapping(value="/test7")
@ResponseBody
public String test7() {
return "hello Test7";
}
# 返回Json对象或集合
- 通过XML的方式
//第一步导入jackjson坐标
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
//第二步在spring-mvc.xml 中进行如下配置
//配置处理器映射器
<bean class=
"org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class=
"org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>
//或者 通过mvc的注解驱动
//需要添加mvc的引用
<mvc:annotation-driven/>
//第三步 测试使用
@RequestMapping(value="/test10")
@ResponseBody
public User test10() {
User user = new User();
user.setUsername("lisi2");
user.setAge(32);
return user;
}
mvc:annotation-driven
在SpringMVC各组件中,处理器映射器、处理器适配器、视图解析器称为SpringMVC的三大组件
使用 mvc:annotation-driven 会自动加载 RequestMappingHandlerMapping(处理映射器)和RequestMappingHandlerAdapter( 处理适配器 ),可用在 Spring-xml.xml 配置文件中使用 mvc:annotation-driven 替代注解处理器和适配器的配置
同时使用 mvc:annotation-driven 底层默认就会集成 jackson 进行对象或集合的 json 格式转换
- 通过注解的方式
//第一步导入jackjson坐标
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
//第二步 测试使用
@RequestMapping(value="/test10")
@ResponseBody
public User test10() {
User user = new User();
user.setUsername("lisi2");
user.setAge(32);
return user;
}
@RequestMapping(value="/test11")
@ResponseBody
public List<User> test11() {
User user1 = new User();
user1.setUsername("lisi1");
user1.setAge(22);
User user2 = new User();
user2.setUsername("lisi2");
user2.setAge(32);
List<User> lUser = new ArrayList<User>();
lUser.add(user1);
lUser.add(user2);
return lUser;
}
# SpringMVC请求数据
Get请求和Post请求的获取方式一样
# 基本类型参数
Controller 中的业务方法的参数名称要与请求参数的 name 一致,参数值会自动映射匹配
//http://localhost:8080/user/test11?username=zhangsan&age=12
@RequestMapping(value="/test11")
@ResponseBody
public void test11(String username, int age) {
System.out.println(username);
System.out.println(age);
}
# 参数绑定注解 @requestParam
当请求的参数名与 Controller 方法中参数名不一致时,就需要通过@RequestParam 注解显示的绑定
- value:与请求参数名称
- required:请求参数是否必须包括,默认是true
- defaultValue:指定默认值
<form action="${pageContext.request.contextPath}/user/test16" method="post">
<input type="text" name="name"><br>
<input type="submit" value="提交"><br>
</form>
@RequestMapping(value="/test16")
@ResponseBody
public void test16(@RequestParam(value="name", required = false, defaultValue = "lzjtu")
String username) {
System.out.println(username);
}
# POJO类型参数
Controller方法中实体参数的属性名与请求参数的实体参数的属性名一致,参数值会自动映射匹配
//http://localhost:8080/user/test12?username=zhangsan&age=12
public class User {
private String username;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", age=" + age +
'}';
}
}
@RequestMapping(value="/test12")
@ResponseBody
//自动映射匹配
public void test12(User user) {
System.out.println(user);
}
---------------------------------------------------------------------------------------
//带引用类型的实体类
//http://localhost/user/test?username=lisi&age=12&address.province=山东&address.city=济南
public class User {
private String username;
private int age;
private Address add;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", age=" + age +
'}';
}
}
@RequestMapping(value="/test12")
@ResponseBody
//自动映射匹配
public void test12(User user) {
System.out.println(user);
}
# 数组类型参数
//http://localhost:8080/user/test13?strs=111&strs=222&strs=333
@RequestMapping(value="/test13")
@ResponseBody
public void test13(String[] strs) {
System.out.println(Arrays.asList(strs));
}
# 集合类型参数
//http://localhost:8080/user/test13?strs=111&strs=222&strs=333
@RequestMapping(value="/test13")
@ResponseBody
public void test14(@RequestParam List<String> strs) {
System.out.println(Arrays.asList(strs));
}
注意
List< String > 一定要添加@RequestParam注解
# Json类型参数
- 添加jackjson坐标
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
- postman传递数据时:body - raw - json
- 开启@EnableWebMvc注解
- 传递 json 格式的数据,在方法参数位置使用 @RequestBody 可以直接接收集合数据
// {zhangsan,li}
@RequestMapping(value="/test15")
@ResponseBody
public void test15(@RequestBody List<String> userList) {
System.out.println(userList);
}
// {name:zhangsan,age=20}
@RequestMapping(value="/test16")
@ResponseBody
public void test16(@RequestBody User user) {
System.out.println(user);
}
// [
// {name:zhangsan,age=20},
// {name:lisi,age=30}
// ]
@RequestMapping(value="/test17")
@ResponseBody
public void test17(@RequestBody List<User> userList) {
System.out.println(user);
}
注意 Required request body is missing(请求主体丢失)异常信息
如果前端调用接口传回参数为空,就会抛出这个异常信息
# 获得请求头
- @RequestHeader:可以获得请求头信息,相当于web阶段学习的request.getHeader(name)
- value:请求头的名称
- required:是否必须携带此请求头
@RequestMapping(value="/test20")
@ResponseBody
public void test20(@RequestHeader(value="User-Agent",required=false) String user_agent) {
System.out.println(user_agent);
}
- @CookieValue:使用@CookieValue可以获得指定Cookie的值
- value:指定cookie的名称
- required:是否必须携带此cookie
@RequestMapping(value="/test21")
@ResponseBody
public void test21(@CookieValue(value = "JSESSIONID") String jsessionId) {
System.out.println(jsessionId);
}
# 获得Servlet相关API
SpringMVC支持使用原始ServletAPI对象作为控制器方法的参数进行注入,常用的对象如下:
- HttpServletRequest
- HttpServletResponse
- HttpSession
@RequestMapping(value="/test19")
@ResponseBody
//mvc框架调用此方法时会自动注入
public void test19(HttpServletRequest req, HttpServletResponse resp, HttpSession session) {
System.out.println(req);
System.out.println(resp);
System.out.println(session);
}
# 请求静态资源的问题
SpringMVC 的前端控制器 DispatcherServlet 的 url-pattern 配置的是 /,代表对所有的资源都进行过滤操作,包括静态资源
<!--在 spring-mvc.xml 配置文件中指定放行的资源-->
<mvc:resources mapping="/js/**" location="/js/"/>
<mvc:default-servlet-handler />
通过程序进行配置
@Configuration
@EnableWebMvc
public classWebConfig extends WebMvcConfigurerAdapter {
@Override
public voidconfigureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
//myCustomDefaultServlet这个是在spring中配置的servletBean的名字
configurer.enable("myCustomDefaultServlet");
}
}
# 请求数据乱码问题
当 post 请求时,数据会出现乱码,我们可以设置一个过滤器来进行编码的过滤
<!--配置全局过滤的filter,设置编码-->
<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>
# Restful 风格的参数
Restful风格的请求是使用 "url+请求方式" 表示一次请求目的的:
- GET:用于获取资源(/user/1 GET => 得到 id = 1 的 user)
- POST:用于新建资源(/user/1 DELETE => 删除 id = 1 的 user)
- PUT:用于更新资源(/user/1 PUT => 更新 id = 1 的 user)
- DELETE:用于删除资源(/user POST => 新增 user)
url 地址 /user/1 中的 1 就是要获得的请求参数,在 SpringMVC 中可以使用占位符进行参数绑定
地址 /user/1 可以写成 /user/{id} 占位符 {id} 对应的就是1。可以使用 @PathVariable 注解进行占位符匹配
// localhost:8080/user/test17/zhangsan
//配合RequestMethod的方式增删改查
@RequestMapping(value="/test17/{name}",method = { RequestMethod.POST })
@ResponseBody
public void test17(@PathVariable("name") String username) {
System.out.println(username);
}
简化方式
// @Controller
// @ResponseBody //所有的方法上都带@ResponseBody时
@RestController //@Controller和@ResponseBody合二为一
@RequestMapping("/book")
public class BookController
{
@Autowired
private BookService bookService;
@PostMapping("")
public Book create(@RequestBody Book book)
{
return this.bookService.create(book);
}
@PostMapping("{id}")
public Book delete(@PathVariable Integer id)
{
return this.bookService.delete(id);
}
@PutMapping("")
public Book update(@RequestBody Book book)
{
Objects.requireNonNull(book);
return this.bookService.update(book);
}
@GetMapping("{id}")
public Book getById(@PathVariable Integer id)
{
return this.bookService.getById(id);
}
@GetMapping("")
public Collection<Book> getList()
{
return this.bookService.getList();
}
}
# 自定义类型转换器
- SpringMVC 默认已经提供了一些常用的类型转换器,例如客户端提交的字符串转换成 int 类型
- 没有提供转换器的数据类型都,就需要自定义,例如:日期类型的数据就需要自定义转换器
# 自定义类型转换器的开发步骤
- 定义转换器类实现Converter接口
public class DateConvert implements Converter<String, Date> {
@Override
public Date convert(String dateStr) {
// 将日期字符串转换成日期对象 返回
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
- 在配置文件中声明转换器
<!--声明转换器-->
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.sylone.convert.DateConvert"></bean>
</list>
</property>
</bean>
- 在 annotation-driven 中引用转换器
<mvc:annotation-driven conversion-service="conversionService"/>
- 测试
@RequestMapping(value="/test18")
@ResponseBody
public void test18(Date date) {
System.out.println(date);
}
# 更简单的实现方式
@RequestMapping(value="/test19")
@ResponseBody
public void test19(@DateTimeFormat(pattern="yyy-MM-dd") Date date) {
System.out.println(user);
}
# 文件上传
文件上传客户端三要素:
- 表单项type="file"
- 表单的提交方式是post
- 表单的enctype属性是多部分表单形式,及enctype="multipart/form-data"
文件上传原理
- 当form表单修改为多部分表单时,request.getParameter()将失效。
- enctype="application/x-www-form-urlencoded"时,form表单的正文内容格式是:key=value&key=value&key=value
- 当form表单的enctype取值为Mutilpart/form-data时,请求正文内容就变成多部分形式
# 单文件上传
- 导入fileupload和io坐标
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotation</artifactId>
<version>2.9.0</version>
</dependency>
- 配置文件上传解析器
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<property name="maxUploadSize" value="500000" />
</bean>
- 编写文件上传代码
@RequestMapping(value="/test22")
@ResponseBody
public void test22(String username, MultipartFile uploadFile1, MultipartFile uploadFile2) {
String originalFilename1 = uploadFile1.getOriginalFilename();
uploadFile1.transferTo(new File("/home/sweetheart/upload/" + originalFilename1));
String originalFilename2 = uploadFile2.getOriginalFilename();
uploadFile2.transferTo(new File("/home/sweetheart/upload/" + originalFilename2));
}
注意 上传参数配置,否则会提示超出了最大限制,其中1048576 bytes代表是1MB
servlet:
multipart:
enabled: true
file-size-threshold: 100MB
max-request-size: 1024MB
max-file-size: 100MB
如果使用nginx报 413 Request Entity Too Large,Nginx默认最大上传1MB文件,需要在nginx.conf配置文件中
http{
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
client_max_body_size 100m;
}
# 多文件上传
多文件上传,只需要将页面修改为多个文件上传,将方法参数MultipartFile类型修改为MultipartFile[]即可
<form action="${pageContext.request.contextPath}/user/test23"
method="post" enctype="multipart/form-data">
名称:<input type="text" name="username">
文件1:<input type="file" name="uploadFile">
文件2:<input type="file" name="uploadFile">
<input type="submit" value="提交">
</form>
@RequestMapping(value="/test23")
@ResponseBody
public void test23(String username, MultipartFile[] uploadFile){
System.out.println(username);
for(MultipartFile multipartFile: uploadFile){
String originalFilename = multipartFile.getOriginalFilename();
multipartFile.transferTo(new File("/home/sweetheart/upload/" + originalFilename));
}
}
# 文件上传+其它数据
// 前端处理
const formData = new FormData()
formData.append("fileImg",file.raw)
formData.append("tbMaterialData",JSON.stringify(form.value))
userMaterialEdit(formData).then(res => {
console.log(res, '用户修改信息');
})
export function userMaterialEdit(data) {
return request({
url: '/templateMaterials/userMaterialUpdate',
method: 'post',
data:data
})
}
// 后端处理
public AjaxResult userMaterialupdate(String tbMaterialData, MuitipartFile fileImg) {
TbMaterial tbMaterial = json.parseobject(tbMaterialData,TbMaterial.class);
}
# SpringMVC的拦截器
# 拦截器(Interceptor)的作用
- 类似于 Servlet 开发中的过滤器 Filter,用于对处理器进行预处理和后处理
- 将拦截器按一定的顺序联结成一条链,这条链称为拦截器链(Interceptor Chain)
- 拦截器也是AOP思想的具体实现
# 多拦截器的执行顺序
执行顺序取决于在配置文件定义的文件顺序
Interceptor01 preHandle执行了……
Interceptor02 preHandle执行了……
demo myInterceptorTest……
Interceptor02 postHandle执行了……
Interceptor01 postHandle执行了……
Interceptor02 afterCompletion执行了……
Interceptor01 afterCompletion执行了……
# XML配置拦截器
- 创建拦截器类实现HandlerInterceptor接口
public class MyHandlerInterceptor1 implements HandlerInterceptor {
//在Controller中的业务方法执行之前执行
public boolean preHandle(HttpServletRequest request, HttpServletResponse response
, Object handler) {
System.out.println("preHandle running...");
String param = request.getParameter("name");
if(param.equals("zhangsan")){
//只有返回true才会往下执行
return true;
}else{
request.getRequestDispatcher("error.jsp").forward(request,response);
return false;
}
}
//在Controller中的业务方法执行之后,视图对象返回之前执行
//主要用于修改ModelAndView
public void postHandle(HttpServletRequest request, HttpServletResponse response
, Object handler, ModelAndView modelAndView) {
modelAndView.addObject("name","lisi");
System.out.println("postHandle running...");
}
//在所以流程结束之后执行
public void afterCompletion(HttpServletRequest request, HttpServletResponse response
, Object handler, Exception ex) {
System.out.println("afterCompletion running...");
}
}
- 配置拦截器
<mvc:interceptors>
<mvc:interceptor>
<!--拦截所有请求-->
<mvc:mapping path="/**"/>
<!--不拦截的路径-->
<mvc:exclude-mapping path="/demo/login"/>
<bean class="com.sylone.interceptor.MyInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
# 注解的方式配置拦截器
- 添加Springmvc所需jar包javax.servlet-api,spring-webmvc,jackson-databind
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>springmvc_12_interceptor</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
- 创建SpringMvcConfig,ServletConfig,暂时不建WebMvcSupport放行静态资源
public class ServletContainersInitConfig
extends AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[0];
}
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
//乱码处理
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("UTF-8");
return new Filter[]{filter};
}
}
@Configuration
@ComponentScan({"com.itheima.controller"})
@EnableWebMvc
public class SpringMvcConfig{
}
- 创建模型类Book
public class Book {
private String name;
private double price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return "Book{" +
"书名='" + name + '\'' +
", 价格=" + price +
'}';
}
}
- 编写Controller
@RestController
@RequestMapping("/books")
public class BookController {
@PostMapping
public String save(@RequestBody Book book){
System.out.println("book save..." + book);
return "{'module':'book save'}";
}
@DeleteMapping("/{id}")
public String delete(@PathVariable Integer id){
System.out.println("book delete..." + id);
return "{'module':'book delete'}";
}
@PutMapping
public String update(@RequestBody Book book){
System.out.println("book update..."+book);
return "{'module':'book update'}";
}
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("book getById..."+id);
return "{'module':'book getById'}";
}
@GetMapping
public String getAll(){
System.out.println("book getAll...");
return "{'module':'book getAll'}";
}
}
- 创建项目拦截器类 拦截器interceptor是在controller包下
@Component //拦截器类要被SpringMVC容器扫描到
//定义拦截处理器类,实现HandlerInterceptor接口
//注意当前类必须受Spring容器控制,并被SpringMvc扫描到
public class ProjectInterceptor implements HandlerInterceptor {
@Override
//处理之前,原始方法调用前执行的内容
public boolean preHandle(HttpServletRequest request, HttpServletResponse response
, Object handler) throws Exception {
System.out.println("preHandle...");
//返回true会放行,返回false会拦截,后面就不会再执行
return true;
}
@Override
//处理之后,原始方法调用后执行的内容
public void postHandle(HttpServletRequest request, HttpServletResponse response
, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandle...");
}
@Override
//拦截完成之后,原始方法调用完成后执行的内容
public void afterCompletion(HttpServletRequest request, HttpServletResponse response
, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion...");
}
}
- SpringMvcSupport类或SpringMvcConfig类中配置拦截器类
- 方法一(底层麻烦): SpringMvcSupport 在config目录下
@Configuration public class SpringMvcSupport extends WebMvcConfigurationSupport { //注入项目拦截器 @Autowired private ProjectInterceptor projectInterceptor; //添加资源处理器 @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/pages/**").addResourceLocations("/pages/"); } //添加拦截器 @Override protected void addInterceptors(InterceptorRegistry registry) { //配置拦截器 registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*" ); //如果只拦截/books,发送http://localhost/books/100后会发现拦截器没有被执行 //registry.addInterceptor(projectInterceptor).addPathPatterns("/books"); } }
- 方法二(简单快速):在SpringMvcConfig中添加拦截器,淘汰SpringMvcSupport
@Configuration //package1.config主要为了扫描项目拦截器类、ServletContainersInitConfig类 @ComponentScan({"package1.controller","package1.config"}) @EnableWebMvc public class SpringMvcConfig implements WebMvcConfigurer { @Autowired private ProjectInterception projectInterception; //添加拦截器 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(projectInterception).addPathPatterns("/books","/books/*"); //如果只拦截/books,发送http://localhost/books/100后会发现拦截器没有被执行 //registry.addInterceptor(projectInterceptor).addPathPatterns("/books"); } //添加资源处理器 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/pages/**").addResourceLocations("/pages/"); registry.addResourceHandler("/js/**").addResourceLocations("/js/"); registry.addResourceHandler("/css/**").addResourceLocations("/css/"); registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/"); } }
- 步骤3:SpringMVC添加SpringMvcSupport包扫描
@Configuration @ComponentScan({"com.itheima.controller","com.itheima.config"}) @EnableWebMvc public class SpringMvcConfig{ }
# SpringMVC异常处理
SpringMVC中的异常处理思路是:当Dao、Service、Controller出现异常时都通过throws Exception向上抛出,最后由SpringMVC前端控制器交由异常处理器进行异常处理
# XML配置的方式
# 自带的简单异常处理处
SpringMVC已经定义好了的异常处理器,在使用时可以根据项目情况进行相应异常与视图的映射配置
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<!--当发生的异常没有被配置时,就会跳转到默认的页面-->
<property name="defaultErrorView" value="default_error"/>
<property name="exceptionMappings">
<map>
<!--key:异常类型,value:异常发生时跳转的页面-->
<entry key="java.lang.NullPointerException" value="null_error"/>
<entry key="java.lang.NumberFormatException" value="format_error"/>
</map>
</property>
</bean>
# 自定义异常处理器
- 创建创建异常处理器类并实现HandlerExceptionResolver
public class MyExceptionResolver implements HandlerExceptionResolver {
@Override
//返回值ModelAndView:跳转的错误视图
public ModelAndView resolveException(HttpServletRequest httpServletRequest
, HttpServletResponse httpServletResponse, Object o, Exception e) {
ModelAndView mav = new ModelAndView();
//Exception e:接收到的异常对象
if(e instanceof MyException){
mav.addObject("info","自定义异常")
}
// 发生异常时跳转的页面
mav.setViewName("default_error");
return mav;
}
}
- 配置自定义异常处理器
<bean id="exceptionResolver" class="com.sylone.exception.MyExceptionResolver"/>
# 注解的方式
# 自定义系统级异常
public class SystemException extends RuntimeException{
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public SystemException(Integer code,String message ) {
super(message);
this.code = code;
}
public SystemException(Integer code,String message, Throwable cause ) {
super(message, cause);
this.code = code;
}
}
# 自定义业务级异常
public class BusinessException extends RuntimeException{
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public BusinessException(Integer code, String message ) {
super(message);
this.code = code;
}
public BusinessException(Integer code, String message, Throwable cause ) {
super(message, cause);
this.code = code;
}
}
# 触发定义异常
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
public Book getById(Integer id) {
//模拟业务异常
if(id == 1){
throw new BusinessException(Code.BUSINESS_ERR,"访问连接过多异常");
}
//模拟系统异常
try {
int i = 1/0;
}catch (Exception exception){
throw new SystemException(Code.SYSTEM_ERR,"服务器访问超时,请重试",exception);
}
return bookDao.getById(id);
}
public List<Book> getAll() {
return bookDao.getAll();
}
}
# 拦截并处理异常
//可以为应用程序中的所有控制器方法做增强
//@ControllerAdvice
//Rest风格开发的控制器类做增强,@ResponseBody+@Component
@RestControllerAdvice
public class ProjectExceptionAdvice {
@ExceptionHandler(Exception.class)
public Result doException(Exception exception) {
//记录日志(错误堆栈)
//发送消息给运维
//发送邮件给开发人员,exception对象发送给开发人员
System.out.println("其他异常被捕获");
return new Result(Code.SYSTEM_UNKNOW_ERR, null, "系统繁忙请稍后再试");
}
@ExceptionHandler(SystemException.class)
public Result doSystemException(SystemException exception) {
//记录日志(错误堆栈)
//发送消息给运维
//发送邮件给开发人员,exception对象发送给开发人员
System.out.println("系统异常被捕获");
return new Result(exception.getCode(), null, exception.getMessage());
}
@ExceptionHandler(BusinessException.class)
public Result doSystemException(BusinessException exception) {
System.out.println("业务异常被捕获");
return new Result(exception.getCode(), null, exception.getMessage());
}
}
注意
SpringBoot的异常处理和这个一样
# SSM框架整合
# xml的方式
# 导入Maven坐标
<dependencies>
<!--spring相关-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--servlet和jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<!--mybatis相关-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--mybatis整合spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
# 编写实体类
public class Account {
private Integer id;
private String name;
private Double money;
}
# 编写Mapper接口
public interface AccountMapper {
public void save(Account account);
public List<Account> findAll();
}
# 编写Service接口
public interface AccountService {
public void save(Account account);
public List<Account> findAll();
}
# 编写Service接口实现
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountMapper accountMapper;
public void save(Account account) {
accountMapper.save(account);
}
public List<Account> findAll() {
return accountMapper.findAll();
}
}
# 编写Controller
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
// 保存
// produces 类似response.contentType("text/html;charset=UTF-8")
@RequestMapping(value = "/save", produces = "text/html;charset=UTF-8")
@ResponseBody
public String save(Account account){
accountService.save(account);
return "保存成功";
}
// 查询
@RequestMapping("/findAll")
public ModelAndView findAll(){
List<Account> accountList = accountService.findAll();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("accountList", accountList);
modelAndView.setViewName("accountList");
return modelAndView;
}
}
# 编写添加页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>添加账户表单信息</h1>
<form name="accountForm"
action="${pageContext.request.contextPath}/account/save"
method="post">
账户名称:<input type="text" name="name"><br />
账户金额:<input type="text" name="money"><br />
<input type="submit" value="提交"><br />
</form>
</body>
</html>
# 编写列表页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>展示账户数据列表</h1>
<table border="1">
<tr>
<th>账户id</th>
<th>账户名称</th>
<th>账户金额</th>
</tr>
<c:forEach items="${accountList}" var="account">
<tr>
<td>${account.id}</td>
<td>${account.name}</td>
<td>${account.money}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
# 编写配置文件
- jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
- log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=info, stdout
- web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!--配置spring监听器-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--springmvc前端控制器-->
<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:spring-mvc.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>
- 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和mapper-->
<context:component-scan base-package="com.lzjtu">
<!--排除controller的扫描-->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!--加载properties文件-->
<context:property-placeholder location="classpath:jdbc.properties" />
<!--配置数据源信息-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}" />
<property name="jdbcUrl" value="${jdbc.url}" />
<property name="user" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!--整合mybatis-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!--加载mybatis核心文件-->
<property name="configLocation" value="classpath:sqlMapConfig-spring.xml" />
</bean>
<!--扫描mapper所在的包 为mapper创建实现类-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.lzjtu.mapper" />
</bean>
<!--声明式事务控制-->
<!--平台事务管理器-->
<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="*"/>
</tx:attributes>
</tx:advice>
<!--事务的aop织入-->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.lzjtu.service.impl.*.*(..))"></aop:advisor>
</aop:config>
</beans>
- spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<!--组件扫描 扫描controller-->
<context:component-scan base-package="com.lzjtu.controller"/>
<!--配置mvc注解驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--内部资源视图解析器-->
<bean id="resourceViewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!--开放静态资源访问权限-->
<mvc:default-servlet-handler />
</beans>
- AccountMapper.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">
<mapper namespace="com.lzjtu.mapper.AccountMapper">
<insert id="save" parameterType="account">
insert into account values (#{id},#{name},#{money})
</insert>
<select id="findAll" resultType="account">
select * from account
</select>
</mapper>
- sqlMapperConfig.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>
<!--定义别名-->
<typeAliases>
<!-- <typeAlias type="com.lzjtu.domain.Account" alias="account" />-->
<package name="com.lzjtu.domain"/>
</typeAliases>
</configuration>
# Java代码的方式
# 配置文件
- 导入坐标
- SpringMVC相关:javax.servlet-api,spring-webmvc(包括了spring-context),javkson-databind
- Spring相关:spring-jdbc,spring-test,junit
- 数据库相关:mybatis,mybatis-spring,mysql,druid
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>springmvc_08_ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
- 创建SpringConfig配置类
@Configuration
@ComponentScan({"com.itheima.service"})
//加载properties,别忘了classpath:
@PropertySource("classpath:jdbc.properties")
//导入Mybatis配置类
@Import({JdbcConfig.class,MyBatisConfig.class})
//启用事务
@EnableTransactionManagement
public class SpringConfig {
}
- 创建SpringMVC配置类
@Configuration
@ComponentScan("com.itheima.controller")
@EnableWebMvc
public class SpringMvcConfig {
}
- 创建Servlet配置类
public class ServletConfig extends AbstractAnnotationConfigDispatcherServletInitializer {
//加载Spring配置类
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
//加载SpringMVC配置类
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
//设置SpringMVC请求地址拦截规则
protected String[] getServletMappings() {
return new String[]{"/"};
}
//设置post请求中文乱码过滤器
@Override
protected Filter[] getServletFilters() {
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding("utf-8");
return new Filter[]{filter};
}
}
- 创建jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm_db
jdbc.username=root
jdbc.password=root
- 创建JdbcConfig配置类
public class JdbcConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Bean
public DataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
//平台事务管理器
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource){
DataSourceTransactionManager ds = new DataSourceTransactionManager();
ds.setDataSource(dataSource);
return ds;
}
}
- 创建MybatisConfig配置类
public class MyBatisConfig {
//MyBatisConfig 配置类需要两个bean被IOC容器管理
//SqlSessionFactoryBean可以自动获得SqlSessionFactory
//MapperScannerConfigurer扫描mapper所在的包
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setTypeAliasesPackage("com.itheima.domain");
return factoryBean;
}
//Mapper扫描配置器MapperScannerConfigurer
@Bean
public MapperScannerConfigurer mapperScannerConfigurer(){
MapperScannerConfigurer msc = new MapperScannerConfigurer();
msc.setBasePackage("com.itheima.dao");
return msc;
}
}
# 代码实现
- 创建数据库及表
create database ssm_db character set utf8;
use ssm_db;
create table tbl_book(
id int primary key auto_increment,
type varchar(20),
name varchar(50),
description varchar(255)
)
- 编写Book模型类
public class Book {
private Integer id;
private String type;
private String name;
private String description;
//getter...setter...toString省略
}
- 编写Dao接口
@Repository
public interface BookDao {
//@Insert("insert into tbl_book values(null,#{type},#{name},#{description})")
@Insert("insert into tbl_book (type,name,description) values(#{type},#{name},#{description})")
public int save(Book book);
@Update("update tbl_book set type = #{type}, name = #{name}, description = #{description} where id = #{id}")
public int update(Book book);
@Delete("delete from tbl_book where id = #{id}")
public int delete(Integer id);
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
@Select("select * from tbl_book")
public List<Book> getAll();
}
- 编写Service接口和实现类
@Transactional
public interface BookService {
/**
* 保存
* @param book
* @return
*/
public boolean save(Book book);
/**
* 修改
* @param book
* @return
*/
public boolean update(Book book);
/**
* 按id删除
* @param id
* @return
*/
public boolean delete(Integer id);
/**
* 按id查询
* @param id
* @return
*/
public Book getById(Integer id);
/**
* 查询全部
* @return
*/
public List<Book> getAll();
}
@Service
public class BookServiceImpl implements BookService {
@Autowired
private BookDao bookDao;
public boolean save(Book book) {
return bookDao.save(book) > 0;
}
public boolean update(Book book) {
return bookDao.update(book) > 0;
}
public boolean delete(Integer id) {
return bookDao.delete(id) > 0;
}
public Book getById(Integer id) {
return bookDao.getById(id);
}
public List<Book> getAll() {
return bookDao.getAll();
}
}
- 编写Contorller类
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@PostMapping
public boolean save(@RequestBody Book book) {
return bookService.save(book);
}
@PutMapping
public boolean update(@RequestBody Book book) {
return bookService.update(book);
}
@DeleteMapping("/{id}")
public boolean delete(@PathVariable Integer id) {
return bookService.delete(id);
}
@GetMapping("/{id}")
public Book getById(@PathVariable Integer id) {
return bookService.getById(id);
}
@GetMapping
public List<Book> getAll() {
return bookService.getAll();
}
}
# 单元测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class BookServiceTest {
@Autowired
private BookService bookService;
@Test
public void testGetById(){
Book book = bookService.getById(1);
System.out.println(book);
}
@Test
public void testGetAll(){
List<Book> all = bookService.getAll();
System.out.println(all);
}
}
# 统一结果封装,前后端数据传输协议
对于结果封装,我们应该是在表现层进行处理,所以我们把Result类和Code类放在controller包下
- 创建Result类
public class Result {
//描述统一格式中的数据
private Object data;
//描述统一格式中的编码,用于区分操作,可以简化配置0或1表示成功失败
private Integer code;
//描述统一格式中的消息,可选属性
private String msg;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Result() {
}
//构造方法是方便对象的创建
public Result(Integer code,Object data) {
this.data = data;
this.code = code;
}
//构造方法是方便对象的创建
public Result(Integer code, Object data, String msg) {
this.data = data;
this.code = code;
this.msg = msg;
}
}
::: 注意 一定要加get和set方法,否则会报错:No converter found for return value of type :::
- 定义返回状态码Code类
//返回状态码,1结尾是成功,0结尾是失败
public class Code {
public static final Integer SAVE_OK = 20011;
public static final Integer DELETE_OK = 20021;
public static final Integer UPDATE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer SAVE_ERR = 20010;
public static final Integer DELETE_ERR = 20020;
public static final Integer UPDATE_ERR = 20030;
public static final Integer GET_ERR = 20040;
}
- 修改Controller类的返回值
//统一每一个控制器方法返回值
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@PostMapping
public Result save(@RequestBody Book book) {
boolean flag = bookService.save(book);
return new Result(flag ? Code.SAVE_OK:Code.SAVE_ERR,flag);
}
@PutMapping
public Result update(@RequestBody Book book) {
boolean flag = bookService.update(book);
return new Result(flag ? Code.UPDATE_OK:Code.UPDATE_ERR,flag);
}
@DeleteMapping("/{id}")
public Result delete(@PathVariable Integer id) {
boolean flag = bookService.delete(id);
return new Result(flag ? Code.DELETE_OK:Code.DELETE_ERR,flag);
}
@GetMapping("/{id}")
public Result getById(@PathVariable Integer id) {
Book book = bookService.getById(id);
Integer code = book != null ? Code.GET_OK : Code.GET_ERR;
String msg = book != null ? "" : "数据查询失败,请重试!";
return new Result(code,book,msg);
}
@GetMapping
public Result getAll() {
List<Book> bookList = bookService.getAll();
Integer code = bookList != null ? Code.GET_OK : Code.GET_ERR;
String msg = bookList != null ? "" : "数据查询失败,请重试!";
return new Result(code,bookList,msg);
}
}
- 标准结果类代码
//以前是把data设为Object类型,现在用泛型格式,都能实现。
@Data
public class R<T> {
private Integer code; //编码:1成功,0和其它数字为失败
private String msg; //错误信息
private T data; //数据
//静态类,controller返回时直接return R.success(T);
public static <T> R<T> success(T object) {
R<T> r = new R<T>();
r.data = object;
r.code = 1;
return r;
}
public static <T> R<T> error(String msg) {
R r = new R();
r.msg = msg;
r.code = 0;
return r;
}
//动态数据
private Map map = new HashMap();
//添加动态数据
public R<T> add(String key, Object value) {
this.map.put(key, value);
return this;
}
}
# 统一异常处理
异常分类
- 业务异常(BusinessException):用户行为产生的异常
- 系统异常(SystemException):项目运行过程中可预计但无法避免的异常
- 其他异常(Exception):编程人员未预期到的异常
创建一个exception包,包含定义三种项目异常的类
//自定义系统异常处理器,继承运行时异常RuntimeException,用于封装异常信息,对异常进行分类
public class SystemException extends RuntimeException{
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public SystemException(Integer code, String message) {
super(message);
this.code = code;
}
public SystemException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
}
//自定义业务异常处理器,用于封装异常信息,对异常进行分类
public class BusinessException extends RuntimeException{
private Integer code;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
}
public BusinessException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
}
- 模拟系统异常、业务异常
public Book getById(Integer id) {
//模拟业务异常,包装成自定义异常
if(id == 1){
throw new BusinessException(Code.BUSINESS_ERR,"请不要使用你的技术挑战我的耐性!");
}
//模拟系统异常,将可能出现的异常进行包装,转换成自定义异常
try{
int i = 1/0;
}catch (Exception e){
throw new SystemException(Code.SYSTEM_TIMEOUT_ERR,"服务器访问超时,请重试!",e);
}
return bookDao.getById(id);
}
- 为了使code看着更专业些,我们在Code类中再新增需要的属性
//状态码
public class Code {
public static final Integer SAVE_OK = 20011;
public static final Integer DELETE_OK = 20021;
public static final Integer UPDATE_OK = 20031;
public static final Integer GET_OK = 20041;
public static final Integer SAVE_ERR = 20010;
public static final Integer DELETE_ERR = 20020;
public static final Integer UPDATE_ERR = 20030;
public static final Integer GET_ERR = 20040;
public static final Integer SYSTEM_ERR = 50001;
public static final Integer SYSTEM_TIMEOUT_ERR = 50002;
public static final Integer SYSTEM_UNKNOWN_ERR = 59999;
public static final Integer BUSINESS_ERR = 60002;
}
- 处理器类中处理自定义异常
//@RestControllerAdvice用于标识当前类为REST风格对应的异常处理器
//此注解自带@ResponseBody注解与@Component注解
@RestControllerAdvice
public class ProjectExceptionAdvice {
//@ExceptionHandler用于设置当前处理器类对应的异常类型
@ExceptionHandler(SystemException.class)
public Result doSystemException(SystemException ex){
//记录日志
//发送消息给运维
//发送邮件给开发人员,ex对象发送给开发人员
return new Result(ex.getCode(),null,ex.getMessage());
}
@ExceptionHandler(BusinessException.class)
public Result doBusinessException(BusinessException ex){
return new Result(ex.getCode(),null,ex.getMessage());
}
//除了自定义的异常处理器,保留对Exception类型的异常处理,用于处理非预期的异常
@ExceptionHandler(Exception.class)
public Result doOtherException(Exception ex){
//记录日志
//发送消息给运维
//发送邮件给开发人员,ex对象发送给开发人员
return new Result(Code.SYSTEM_UNKNOW_ERR,null,"系统繁忙,请稍后再试!");
}
}