根据黑马程序员的课程资料整理所得,仅用于学习使用,如有侵权,请联系删除
SpringMVC概述
-
SpringMVC是一种基于Java实现MVC模型的轻量级Web框架
-
优点:
- 使用简单、开发便捷(相比于Servlet)
- 灵活性强
SpringMVC入门案例(后续项目创建不再讲解)
- 创建一个maven项目
- 导入jar包
<?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>"模块所在位置"</groupId>
<artifactId>springmvc_01_quickstart</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>
</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>
- 创建配置类
@Configuration//springmvc配置类,本质上还是一个spring配置类
@ComponentScan("controller")
public class SpringMvcConfig {
}
- 创建Controller类
@Controller
public class UserController {
@RequestMapping("/save")
public void save(){
System.out.println("user save ...");
}
}
- 使用ServletContainersInitConfig配置类替换web.xml
public class ServletContainersInitConfig extends
AbstractDispatcherServletInitializer {
//加载springmvc配置类
protected WebApplicationContext createServletApplicationContext() {
//初始化WebApplicationContext对象
AnnotationConfigWebApplicationContext ctx = new
AnnotationConfigWebApplicationContext();
//加载指定配置类
ctx.register(SpringMvcConfig.class);
return ctx;
}
//设置由springmvc控制器处理的请求映射路径
protected String[] getServletMappings() {
return new String[]{"/"};
}
//加载spring配置类
protected WebApplicationContext createRootApplicationContext() {
return null;
}
}
- 配置Tomcat环境
- 启动运行项目,浏览器访问,后台没有指定返回的页面
- 修改Controller返回值解决上述问题,使后台响应json数据
//定义表现层控制器bean
@Controller
public class UserController {
//设置映射路径为/save,即外部访问路径
@RequestMapping("/save")
//设置当前操作返回结果为指定json数据(本质上是一个字符串信息)
@ResponseBody
public String save(){
System.out.println("user save ...");
return "{'info':'springmvc'}";
}
//设置映射路径为/delete,即外部访问路径
@RequestMapping("/delete")
@ResponseBody
public String delete(){
System.out.println("user save ...");
return "{'info':'springmvc'}";
}
}
入门案例流程分析
1.启动服务器初始化过程
- 服务器启动,执行ServletContainersInitConfig类,初始化web容器
- 功能类似于以前的web.xml
- 执行createServletApplicationContext方法,创建了WebApplicationContext对象
- 该方法加载SpringMVC的配置类SpringMvcConfig来初始化SpringMVC的容器
- 加载SpringMvcConfig配置类
- 执行@ComponentScan加载对应的bean
- 扫描指定包及其子包下所有类上的注解,如Controller类上的@Controller注解
- 加载UserController,每个@RequestMapping的名称对应一个具体的方法
- 此时就建立了 /save 和 save方法的对应关系
- 执行getServletMappings方法,设定SpringMVC拦截请求的路径规则
- 代表所拦截请求的路径规则,只有被拦截后才能交给SpringMVC来处理请求
2.单次请求过程
- 发送请求http://localhost/save
- web容器发现该请求满足SpringMVC拦截规则,将请求交给SpringMVC处理
- 解析请求路径/save
- 由/save匹配执行对应的方法save()
- 上面的第五步已经将请求路径和方法建立了对应关系,通过/save就能找到对应的save方法
- 执行save()
- 检测到有@ResponseBody直接将save()方法的返回值作为响应体返回给请求方
SpringMVC_Bean加载控制
1.springmvc对应bean加载
在SpringMVC的配置类SpringMvcConfig中使用注解@ComponentScan,我们只需要将其扫描范围设置到controller即可
2.spring对应bean加载
方式一:修改Spring配置类,设定扫描范围为精准范围。
@Configuration
@ComponentScan({"service","dao"})
public class SpringConfig {
}
方式二:修改Spring配置类,设定扫描范围,排除掉controller包中的bean
@Configuration
@ComponentScan(value="",
excludeFilters=@ComponentScan.Filter(
type = FilterType.ANNOTATION,
classes = Controller.class
)
)
public class SpringConfig {
}
- excludeFilters属性:设置扫描加载bean时,排除的过滤规则
- type属性:设置排除规则,当前使用按照bean定义时的注解类型进行排除
- ANNOTATION:按照注解排除
- ASSIGNABLE_TYPE:按照指定的类型过滤
- ASPECTJ:按照Aspectj表达式排除,基本上不会用
- REGEX:按照正则表达式排除
- CUSTOM:按照自定义规则排除
- classes属性:设置排除的具体注解类,当前设置排除@Controller定义的bean
3.利用Spring提供的一种更简单的配置方式去创建AnnotationConfigWebApplicationContext对象
public class ServletContainersInitConfig extends
AbstractAnnotationConfigDispatcherServletInitializer {
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}
protected Class<?>[] getServletConfigClasses() {
return new Class[]{SpringMvcConfig.class};
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
SpringMVC_设置请求映射路径
- 团队多人开发,每人设置不同的请求路径,冲突问题解决方式:优化路径配置
//例如
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping("/save")
@ResponseBody
public String save(){
System.out.println("user save ...");
return "{'module':'user save'}";
}
@RequestMapping("/delete")
@ResponseBody
public String save(){
System.out.println("user delete ...");
return "{'module':'user delete'}";
}
}
@Controller
@RequestMapping("/book")
public class BookController {
@RequestMapping("/save")
@ResponseBody
public String save(){
System.out.println("book save ...");
return "{'module':'book save'}";
}
}
*注意:当类上和方法上都添加了@RequestMapping注解,前端发送请求的时候,要和两个注解的value值相加匹配才能访问到
SpringMVC_请求与响应
一.请求
- 请先下载postman软件,教程:接口测试工具Postman接口测试图文教程
1.GET发送参数
http://localhost/commonParam?name=itcast&age=15
接收参数:
@Controller
public class UserController {
@RequestMapping("/commonParam")
@ResponseBody
public String commonParam(String name,int age){
System.out.println("普通参数传递 name ==> "+name);
System.out.println("普通参数传递 age ==> "+age);
return "{'module':'commonParam'}";
}
}
2.GET请求中文乱码
如果我们传递的参数中有中文,你会发现接收到的参数会出现中文乱码问题。
发送请求: http://localhost/commonParam?name=张三&age=18
- 出现乱码的原因相信大家都清楚,Tomcat8.5以后的版本已经处理了中文乱码的问题,但是IDEA中的Tomcat插件目前只到Tomcat7,所以需要修改pom.xml来解决GET请求中文乱码问题
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>80</port><!--tomcat端口号-->
<path>/</path> <!--虚拟目录-->
<uriEncoding>UTF-8</uriEncoding><!--访问路径编解码字符集-->
</configuration>
</plugin>
</plugins>
</build>
3.POST发送参数
接收方式与get保持一致即可
4.POST请求中文乱码
解决方案:配置过滤器
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};
}
}
五种类型参数传递
1. 普通参数
前端给的是name ,后台接收使用的是userName ,两个名称对不上的解决方法:
- 使用@RequestParam注解
- 发送请求与参数:
http://localhost/commonParamDifferentName?name=张三&age=18
- 后台接收参数:
@RequestMapping("/commonParamDifferentName")
@ResponseBody
public String commonParamDifferentName(@RequestPaam("name") String
userName , int age){
System.out.println("普通参数传递 userName ==> "+userName);
System.out.println("普通参数传递 age ==> "+age);
return "{'module':'common param different name'}";
}
2. POJO类型参数
- 此时需要使用前面准备好的POJO类,先来看下User
public class User {
private String name;
private int age;
//setter...getter...略
}
- 发送请求和参数:
- 后台接收参数:
//POJO参数:请求参数与形参对象中的属性对应即可完成参数传递
@RequestMapping("/pojoParam")
@ResponseBody
public String pojoParam(User user){
System.out.println("pojo参数传递 user ==> "+user);
return "{'module':'pojo param'}";
//请求参数key的名称要和POJO中属性的名称一致,否则无法封装。
}
3. 嵌套POJO类型参数
- 如果POJO对象中嵌套了其他的POJO类,如
public class Address {
private String province;
private String city;
//setter...getter...略
}
public class User {
private String name;
private int age;
private Address address;
//setter...getter...略
//嵌套POJO参数:请求参数名与形参对象属性名相同,按照对象层次结构关系即可接收嵌套POJO属
//性参数
}
- 请求参数:
- 后台接收参数:
//POJO参数:请求参数与形参对象中的属性对应即可完成参数传递
@RequestMapping("/pojoParam")
@ResponseBody
public String pojoParam(User user){
System.out.println("pojo参数传递 user ==> "+user);
return "{'module':'pojo param'}";
}
4. 数组类型参数
- 请求
- 后台接收参数:
//数组参数:同名请求参数可以直接映射到对应名称的形参数组对象中
@RequestMapping("/arrayParam")
@ResponseBody
public String arrayParam(String[] likes){
System.out.println("数组参数传递 likes ==> "+ Arrays.toString(likes));
return "{'module':'array param'}";
}
5. 集合类型参数
- 发送请求和参数:
- 后台接收参数:
//集合参数:同名请求参数可以使用@RequestParam注解映射到对应名称的集合对象中作为数据
@RequestMapping("/listParam")
@ResponseBody
public String listParam(@RequestParam List<String> likes){
//如果没有@RequestParam则会报错,因为SpringMVC将List看做是一个POJO对象来处理,将其创建一个对象并准备把前端的数
//据封装到对象中,但是List是一个接口无法创建对象,所以报错
System.out.println("集合参数传递 likes ==> "+ likes);
return "{'module':'list param'}";
}
json数据传递参数
- 准备工作:
- 1.添加依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
- 2.开启SpringMVC注解支持
@Configuration
@ComponentScan("controller")
//开启json数据类型自动转换
@EnableWebMvc
public class SpringMvcConfig {
}
1.JSON普通数组
- 1.PostMan发送JSON数据
- 2.参数前添加@RequestBody
//使用@RequestBody注解将外部传递的json数组数据映射到形参的集合对象中作为数据
@RequestMapping("/listParamForJson")
@ResponseBody
public String listParamForJson(@RequestBody List<String> likes){
System.out.println("list common(json)参数传递 list ==> "+likes);
return "{'module':'list common for json param'}";
}
2.JSON对象数据
- 请求和数据的发送:
{
"name":"itcast",
"age":15,
"address":{
"province":"beijing",
"city":"beijing"
}
}
- 后端接收数据:
@RequestMapping("/pojoParamForJson")
@ResponseBody
public String pojoParamForJson(@RequestBody User user){
System.out.println("pojo(json)参数传递 user ==> "+user);
return "{'module':'pojo for json param'}";
}
3.JSON对象数组
- 请求和数据的发送:
[
{"name":"itcast","age":15},
{"name":"itheima","age":12}
]
- 后端接收数据:
@RequestMapping("/listPojoParamForJson")
@ResponseBody
public String listPojoParamForJson(@RequestBody List<User> list){
System.out.println("list pojo(json)参数传递 list ==> "+list);
return "{'module':'list pojo for json param'}";
}
日期类型参数传递
- 做好准备工作(同上)
- 发送请求:
http://localhost/dataParam?date=2088/08/08&date1=2088-08-08&date2=2088/08/08 8:08:08
- 接收请求:
@RequestMapping("/dataParam")
@ResponseBody
public String dataParam(Date date,
@DateTimeFormat(pattern="yyyy-MM-dd") Date date1,
//使用@DateTimeFormat进行格式转换
@DateTimeFormat(pattern="yyyy/MM/dd HH:mm:ss") Date
date2)
System.out.println("参数传递 date ==> "+date);
System.out.println("参数传递 date1(yyyy-MM-dd) ==> "+date1);
System.out.println("参数传递 date2(yyyy/MM/dd HH:mm:ss) ==> "+date2);
return "{'module':'data param'}";
}
二.响应
- 准备工作:添加依赖,以下为需新添加的依赖
- 发送请求:
此处不涉及到页面跳转,因为我们现在发送的是post请求,使用PostMan进行 测试,输入地址http://localhost/...访问
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
1.响应页面
- 1.设置返回页面
@Controller
public class UserController {
@RequestMapping("/toJumpPage")
//注意
//1.此处不能添加@ResponseBody,如果加了该注入,会直接将page.jsp当字符串返回前端
//2.方法需要返回String
public String toJumpPage(){
System.out.println("跳转页面");
return "page.jsp";
}
}
- 2.运行测试
2.响应数据
-
文本数据
- 响应:
@Controller
public class UserController {
@RequestMapping("/toText")
//注意此处该注解就不能省略,如果省略了,会把response text当前页面名称去查找,如果没有
回报404错误
@ResponseBody
public String toText(){
System.out.println("返回纯文本数据");
return "response text";
}
}
- json数据
- 响应POJO对象
@Controller
public class UserController {
@RequestMapping("/toJsonPOJO")
@ResponseBody//注意添加该注解
public User toJsonPOJO(){
System.out.println("返回json对象数据");
User user = new User();
user.setName("itcast");
user.setAge(15);
return user;
}
}
SpringMVC_REST风格
1.REST简介
- REST(Representational State Transfer),表现形式状态转换,它是一种软件架构风格
当我们想表示一个网络资源的时候,可以使用两种方式:- 传统风格资源描述形式
- http://localhost/user/getById?id=1 查询id为1的用户信息
- http://localhost/user/saveUser 保存用户信息
- REST风格描述形式
- http://localhost/user/1
- http://localhost/user
- 传统风格资源描述形式
- 传统方式一般是一个请求url对应一种操作,这样做不仅麻烦,也不安全,因为会程序的人读取了你的
请求url地址,就大概知道该url实现的是一个什么样的操作。
查看REST风格的描述,你会发现请求地址变的简单了,并且光看请求URL并不是很能猜出来该URL的
具体功能 - 所以REST的优点有:
- 隐藏资源的访问行为,无法通过地址得知对资源是何种操作
- 书写简化
- 按照REST风格访问资源时使用行为动作区分对资源进行了何种操作
- http://localhost/users 查询全部用户信息 GET (查询)
- http://localhost/users/1 查询指定用户信息 GET (查询)
- http://localhost/users 添加用户信息 POST (新增/保存)
- http://localhost/users 修改用户信息 PUT (修改/更新)
- http://localhost/users/1 删除用户信息 DELETE (删除)
2.RESTful入门案例
- 1.设定http请求动作(动词)
method = RequestMethod.
根据对资源进行何种操作来修改method
@RequestMapping(value = "/books/{id}",method = RequestMethod.DELETE)
@ResponseBody
public String delete(@PathVariable Integer id){//id要与上列大括号中/{id}相对应
System.out.println("book delete..." + id);
return "{'module':'book delete'}";
}
- 2.传递路径参数
修改@RequestMapping的value属性,将其中修改为/users/{id},目的是和路径匹配
方法:在方法的形参前添加@PathVariable注解
3.RESTful快速开发
- 问题1:每个方法的@RequestMapping注解中都定义了访问路径/books,重复性太高。
- 问题2:每个方法的@RequestMapping注解中都要使用method属性定义请求方式,重复性太高。
- 问题3:每个方法响应json都需要加上@ResponseBody注解,重复性太高。
- 解决方法:
-
将@RequestMapping提到类上面,用来定义所有方法共同的访问路径。
-
使用@GetMapping @PostMapping @PutMapping @DeleteMapping代替
//@RequestMapping(value = "/{id}",method = RequestMethod.GET)
@GetMapping("/{id}")
- 将ResponseBody提到类上面,让所有的方法都有@ResponseBody的功能,使用@RestController注解替换@Controller与@ResponseBody注解,简化书写
@RestController //@Controller + ReponseBody
- 如:
@RestController //@Controller + ReponseBody
@RequestMapping("/books")
public class BookController {
//@RequestMapping(method = RequestMethod.POST)
@PostMapping
public String save(@RequestBody Book book){
System.out.println("book save..." + book);
return "{'module':'book save'}";
}
//@RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
@DeleteMapping("/{id}")
public String delete(@PathVariable Integer id){
System.out.println("book delete..." + id);
return "{'module':'book delete'}";
}
}
SpringMVC_SSM整合
1.流程分析
(1) 创建工程
- 创建一个Maven的web工程
- pom.xml添加SSM需要的依赖jar包
- 编写Web项目的入口配置类,实现
AbstractAnnotationConfigDispatcherServletInitializer
重写以下方法- getRootConfigClasses() :返回Spring的配置类->需要SpringConfig配置类
- getServletConfigClasses() :返回SpringMVC的配置类->需要SpringMvcConfig配置类
- getServletMappings() : 设置SpringMVC请求拦截路径规则
- getServletFilters() :设置过滤器,解决POST请求中文乱码问题
(2)SSM整合[重点是各个配置的编写]
- SpringConfig
- 标识该类为配置类 @Configuration
- 扫描Service所在的包 @ComponentScan
- 在Service层要管理事务 @EnableTransactionManagement
- 读取外部的properties配置文件 @PropertySource
- 整合Mybatis需要引入Mybatis相关配置类 @Import
- 第三方数据源配置类 JdbcConfig
- 构建DataSource数据源,DruidDataSouroce,需要注入数据库连接四要素, @Bean @Value
- 构建平台事务管理器,DataSourceTransactionManager,@Bean
- Mybatis配置类 MybatisConfig
- 构建SqlSessionFactoryBean并设置别名扫描与数据源,@Bean
- 构建MapperScannerConfigurer并设置DAO层的包扫描
- 第三方数据源配置类 JdbcConfig
- SpringMvcConfig
- 标识该类为配置类 @Configuration
- 扫描Controller所在的包 @ComponentScan
- 开启SpringMVC注解支持 @EnableWebMvc
(3)功能模块[与具体的业务模块有关]
-
创建数据库表
-
根据数据库表创建对应的模型类
-
通过Dao层完成数据库表的增删改查(接口+自动代理)
-
编写Service层[Service接口+实现类]
- @Service
- @Transactional
- 整合Junit对业务层进行单元测试
- @RunWith
- @ContextConfiguration
- @Test
-
编写Controller层
-
接收请求 @RequestMapping @GetMapping @PostMapping @PutMapping @DeleteMapping
-
接收数据 简单、POJO、嵌套POJO、集合、数组、JSON数据类型
- @RequestParam
- @PathVariable
- @RequestBody
-
转发业务层
- @Autowired
-
响应结果
- @ResponseBody
- @ResponseBody
-
-
结构如上:
-
config目录存放的是相关的配置类
-
controller编写的是Controller类
-
dao存放的是Dao接口,因为使用的是Mapper接口代理方式,所以没有实现类包
-
service存的是Service接口,impl存放的是Service实现类
-
resources:存入的是配置文件,如Jdbc.properties
-
webapp:目录可以存放静态资源
-
test/java:存放的是测试类
-
2.统一结果封装
1.表现层与前端数据传输协议定义
-
问题:目前我们就已经有三种数据类型返回给前端,如果随着业务的增长,我们需要返回的数据类型会越来越多。对于前端开发人员在解析数据的时候就比较凌乱了,所以对于前端来说,如果后台能够返回一个统一的数据结果,前端在解析的时候就可以按照一种方式进行解析。
-
解决方法:设置统一数据返回结果类
public class Result{ private Object data; private Integer code; private String msg; }
2.表现层与前端数据传输协议实现
1.创建Result类
public class Result {
//描述统一格式中的数据
private Object data;
//描述统一格式中的编码,用于区分操作,可以简化配置0或1表示成功失败
private Integer code;
//描述统一格式中的消息,可选属性
private String 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;
}
//setter...getter...省略
}
2.定义返回码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;
//SAVE_OK等常量可以根据自己喜好进行设计
}
3.修改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);
}
}
3.异常处理
1.异常处理器介绍及使用
-
在解决问题之前,我们先来看下异常的种类及出现异常的原因:
-
框架内部抛出的异常:因使用不合规导致
-
数据层抛出的异常:因外部服务器故障导致(例如:服务器访问超时)
-
业务层抛出的异常:因业务逻辑书写错误导致(例如:遍历业务书写操作,导致索引异常等)
-
表现层抛出的异常:因数据收集、校验等规则导致(例如:不匹配的数据类型间导致异常)
-
工具类抛出的异常:因工具类书写不严谨不够健壮导致(例如:必要释放的连接长期未释放等)
-
-
看完上面这些出现异常的位置,你会发现,在我们开发的任何一个位置都有可能出现异常,而且这些异常是不能避免的。所以我们就得将异常进行处理。下面给出解决方法:
- 所有的异常均抛出到表现层进行处理
- 表现层将异常进行异常分类
- 使用AOP
-
而SpringMVC已经给我们提供了异常处理器:
@RestControllerAdivce public class ProjectExceptionAdvice { //设置指定异常的处理方案,功能等同于控制器方法,出现异常后终止原始控制器执行,并转入当前方法执行 @ExceptionHandler(Exception.class) public Result doException(Exception ex){ //返回表现层与前端数据传输协议中定义的Result return new Result(... , ... , ""); } }
2.项目异常处理方案
1.异常分类
1.业务异常(BusinessException)
- 规范的用户行为产生的异常
- 用户在页面输入内容的时候未按照指定格式进行数据填写,如在年龄框输入的是字符串
- 不规范的用户行为操作产生的异常
- 如用户故意传递错误数据
2.系统异常
- 项目运行过程中可预计但无法避免的异常
- 比如数据库或服务器宕机
3.其它异常
- 编程人员未预期到的异常,如:用到的文件不存在
2.异常解决方案
- 业务异常(BusinessException)
- 发送对应消息传递给用户,提醒规范操作
- 大家常见的就是提示用户名已存在或密码格式不正确等
- 发送对应消息传递给用户,提醒规范操作
- 系统异常(SystemException)
- 发送固定消息传递给用户,安抚用户
- 系统繁忙,请稍后再试
- 系统正在维护升级,请稍后再试
- 系统出问题,请联系系统管理员等
- 发送特定消息给运维人员,提醒维护
- 可以发送短信、邮箱或者是公司内部通信软件
- 记录日志
- 发消息和记录日志对用户来说是不可见的,属于后台程序
- 发送固定消息传递给用户,安抚用户
- 其他异常(Exception)
- 发送固定消息传递给用户,安抚用户
- 发送特定消息给编程人员,提醒维护(纳入预期范围内)
- 一般是程序没有考虑全,比如未做非空校验等
- 记录日志
3.具体实现
- 自定义异常类,对异常进行分类
//自定义异常处理器,用于封装异常信息,对异常进行分类
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;
}
}
- 将其他异常包成自定义异常
具体的包装方式有:
- 方式一:
try{}catch(){}
在catch中重新throw我们自定义异常即可。 - 方式二:直接throw自定义异常即可
例如:
try{
//发生异常的语句
}catch (Exception e){
throw new SystemException(Code.SYSTEM_TIMEOUT_ERR,"服务器访问超时,请重试!",e);
}
- 处理器类中处理自定义异常
//@RestControllerAdvice用于标识当前类为REST风格对应的异常处理器
@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,"系统繁忙,请稍后再试!");
}
}
- 运行测试
图解
4.前后台协议联调(此处仅提醒添加拦截,不做具体功能)
- 因为添加了静态资源,SpringMVC会拦截,所有需要在SpringConfig的配置类中将静态资源进行放行。
- 新建SpringMvcSupport
@Configuration
public class SpringMvcSupport extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
registry.addResourceHandler("/css/**").addResourceLocations("/css/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
}
因为添加了静态资源,SpringMVC会拦截,所有需要在SpringConfig的配置类中将静态资源进行放行。
- 在SpringMvcConfig中扫描SpringMvcSupport
@Configuration
@ComponentScan({"controller","config"})
@EnableWebMvc
public class SpringMvcConfig {
}
SpringMVC_拦截器
1.拦截器概念
讲解拦截器的概念之前,我们先看一张图:
-
浏览器发送一个请求会先到Tomcat的web服务器
-
Tomcat服务器接收到请求以后,会去判断请求的是静态资源还是动态资源
-
如果是静态资源,会直接到Tomcat的项目部署目录下去直接访问
-
如果是动态资源,就需要交给项目的后台代码进行处理
-
在找到具体的方法之前,我们可以去配置过滤器(可以配置多个),按照顺序进行执行
-
然后进入到到中央处理器(SpringMVC中的内容),SpringMVC会根据配置的规则进行拦截
-
如果满足规则,则进行处理,找到其对应的controller类中的方法进行执行,完成后返回结果
-
如果不满足规则,则不进行处理
-
这个时候,如果我们需要在每个Controller方法执行的前后添加业务,具体该如何来实现?
这个就是拦截器要做的事。
- 拦截器(Interceptor)是一种动态拦截方法调用的机制,在SpringMVC中动态拦截控制器方法的执行
- 作用:
- 在指定的方法调用前后执行预先设定的代码
- 阻止原始方法的执行
- 总结:拦截器就是用来做增强
看完以后,大家会发现
- 拦截器和过滤器在作用和执行顺序上也很相似
所以这个时候,就有一个问题需要思考:拦截器和过滤器之间的区别是什么?
- 归属不同:Filter属于Servlet技术,Interceptor属于SpringMVC技术
- 拦截内容不同:Filter对所有访问进行增强,Interceptor仅针对SpringMVC的访问进行增强
2.入门案例
1.声明拦截器的bean,并实现HandlerInterceptor接口(注意:扫描加载bean)
@Component
//定义拦截器类,实现HandlerInterceptor接口
//注意当前类必须受Spring容器控制
public class ProjectInterceptor implements HandlerInterceptor {
@Override
//原始方法调用前执行的内容
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle...");
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...");
}
}
2.定义配置类,继承 WebMvcConfigurationSupport,实现addInterceptors方法
@Configuration
//配置类,不要忘记SpringMVC添加SpringMvcSupport包扫描
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" );
}
}
3.添加让拦截器并设定拦截的访问路径
@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/*" );
}
}
4.使用标准接口WebMvcConfigurer简化开发
@Configuration
@ComponentScan({" controller"})
@EnableWebMvc
//实现WebMvcConfigurer接口可以简化开发,但具有一定的侵入性
public class SpringMvcConfig implements WebMvcConfigurer {
@Autowired
private ProjectInterceptor projectInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置多拦截器
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
}
}
//此后咱们就不用再写`SpringMvcSupport类了。,但侵入性较强
- 执行流程:
3.拦截器参数
1.前置处理方法
原始方法之前运行preHandle
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
//handler:被调用的处理器对象,本质上是一个方法对象,对反射中的Method对象进行了再包装
return true;
}
使用handler参数,可以获取方法的相关信息,例如
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HandlerMethod hm = (HandlerMethod)handler;
String methodName = hm.getMethod().getName();//可以获取方法的名称
return true;
}
2.后置处理方法
拦截器最后执行的方法,无论原始方法是否执行
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) throws Exception {
System.out.println("afterCompletion");
}
//ex:如果处理器执行过程中出现异常对象,可以针对异常情况进行单独处理
//因为我们现在已经有全局异常处理器类,所以该参数的使用率也不高。
4.拦截器链配置
1.再创建一个拦截器类
2.配置多拦截器
@Configuration
@ComponentScan({"controller"})
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {
@Autowired
private ProjectInterceptor projectInterceptor;
@Autowired
private ProjectInterceptor2 projectInterceptor2;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置多拦截器
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
registry.addInterceptor(projectInterceptor2).addPathPatterns("/books","/books/*");
//拦截器链的运行顺序参照拦截器添加顺序为准
}
}
拦截示意图:
Response response, Object handler) throws Exception {
HandlerMethod hm = (HandlerMethod)handler;
String methodName = hm.getMethod().getName();//可以获取方法的名称
return true;
}
### 2.后置处理方法
拦截器最后执行的方法,无论原始方法是否执行
```java
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) throws Exception {
System.out.println("afterCompletion");
}
//ex:如果处理器执行过程中出现异常对象,可以针对异常情况进行单独处理
//因为我们现在已经有全局异常处理器类,所以该参数的使用率也不高。
4.拦截器链配置
1.再创建一个拦截器类
2.配置多拦截器
@Configuration
@ComponentScan({"controller"})
@EnableWebMvc
public class SpringMvcConfig implements WebMvcConfigurer {
@Autowired
private ProjectInterceptor projectInterceptor;
@Autowired
private ProjectInterceptor2 projectInterceptor2;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//配置多拦截器
registry.addInterceptor(projectInterceptor).addPathPatterns("/books","/books/*");
registry.addInterceptor(projectInterceptor2).addPathPatterns("/books","/books/*");
//拦截器链的运行顺序参照拦截器添加顺序为准
}
}
拦截示意图: