在Spring3.2中,新增了@ControllerAdvice注解。关于这个注解的官方说明https://docs.spring.io/spring-framework/docs/5.0.0.M1/javadoc-api/org/springframework/web/bind/annotation/ControllerAdvice.html

我们可以根据字面意思将这个注解理解为Controller的Advice(在spring aop中,Advice被翻译为“增强”)。

在这个控制器的增强处理中,spring提供了三个注解,来帮助我们对Controller进行增强的操作:

@ExceptionHandler:异常处理器、@InitBinder:初始参数绑定器、@ModelAttribute(模型参数)。

@ControllerAdvice

先来看下@ControllerAdvice的内容,这个注解是使用在Class上,里面有几个参数可以指定basePackages,但由于这个注解只是对Controller的增强,因此只对指定包下的Controller生效(如果在dao或service包中对异常上抛,也是可以抛出到Controller层,并通过搭配该注解进行捕获异常)。

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice {
@AliasFor("basePackages")
String[] value() default {}; @AliasFor("value")
String[] basePackages() default {}; Class<?>[] basePackageClasses() default {}; Class<?>[] assignableTypes() default {}; Class<? extends Annotation>[] annotations() default {};
}

@ExceptionHandler

@ExceptionHandler:这个注解是使用在方法上,可以处理指定的异常。假如异常不在这个范围内,则不会被捕获,可以定义多个不同的异常处理器用来分别处理不同的异常。

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
Class<? extends Throwable>[] value() default {};
}

我们来测试一下@ExceptionHandler

定义一个全局异常处理器,里面指定了两个异常的捕获和处理,一个是IAE,一个是NPE。

@ControllerAdvice
public class GlobalExceptionHandler { @ExceptionHandler(value = IllegalArgumentException.class) //指定异常只处理IAE,也可以指定为Throwable类,可以处理所有的异常。
@ResponseBody //这里添加ResponseBody是为了直接返回字符串到前端,否则会如同Controller一样,将返回的字符串作为视图名处理,向视图发起请求。
public String handler(Exception exception) {
System.out.println("抓住异常,异常原因:");
System.out.println(exception.getMessage());
return "IllegalArgumentException";
} @ExceptionHandler(value = NullPointerException.class)
@ResponseBody
public String handler2(Exception exception) {
System.out.println("抓住异常,异常原因:");
System.out.println(exception.getMessage());
return "NullPointerException";
} }

然后我们定义一个Controller,里面会抛出上面的两种异常

    @GetMapping("users/{id}")
public String getUser(@PathVariable("id") String id) throws Exception {
System.out.println("接收到请求[/users/" + id + "]");
if (id.equals("error")) {
throw new IllegalArgumentException("参数错误!");
} else if (id.equals("null")) {
throw new NullPointerException("id不能为null!");
}
return "testUser";
}

启动项目,分别输入参数为error和null的请求,查看控制台打印数据:

接收到请求[/users/error]
抓住异常,异常原因:
参数错误! 接收到请求[/users/error]
抓住异常,异常原因:
id不能为null!

如果我们在controller里面再抛出一个其他类型的异常,则会直接返回到前端,而不是被交给异常处理器处理。

@InitBinder

这个注解用来对从前端传入的参数进行功能辅助。

具体的辅助功能有很多种。比如我们传了一个String类型的"2019-05-05",但是我们在controller要用Date来获取,默认情况下是会抛出非法参数异常,如下:

因此这个时候需要我们在@InitBinder中配置一个自定义日期格式,如下:

    @InitBinder
public void globalInitBinder(WebDataBinder binder) {
binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
}

这个注解关键的重点在于它的参数WebDataBinder中配置的信息,除了上面的添加自定义格式外,还可以注册其他的类型,如将参数自动存储在Map中。

    @InitBinder
public void globalInitBinder(WebDataBinder binder) {
binder.registerCustomEditor(Integer.class, new CustomMapEditor(HashMap.class));
}

@ModelAttribute

该注解用来在Controller接收参数之前对数据模型进行处理,可以添加或删除相关的数据,比如我们在@ModelAttrbute中配置两个数据name和age

    @ModelAttribute
public void model(Model model) {
model.addAttribute("name", "yxf");
model.addAttribute("age", );
}

然后在Controller的方法中进行配置

    @GetMapping("users/login")
public String test(@ModelAttribute("name")String name, @ModelAttribute("age") int age) {
System.out.println("Name="+name + ";Age="+age);
return "index";
}

配置完成后运行启动类,输入路径"/users/login"不带任何参数。

控制台照样会打印结果:Name=yxf;Age=12

Spring boot--控制器增强的更多相关文章

  1. springboot2.0(一):【重磅】Spring Boot 2.0权威发布

    就在昨天Spring Boot2.0.0.RELEASE正式发布,今天早上在发布Spring Boot2.0的时候还出现一个小插曲,将Spring Boot2.0同步到Maven仓库的时候出现了错误, ...

  2. 业余草分享 Spring Boot 2.0 正式发布的新特性

    就在昨天Spring Boot2.0.0.RELEASE正式发布,今天早上在发布Spring Boot2.0的时候还出现一个小插曲,将Spring Boot2.0同步到Maven仓库的时候出现了错误, ...

  3. 【重磅】Spring Boot 2.0权威发布

    新版本特性 新版本值得关注的亮点有哪些: 基于 Java 8,支持 Java 9 也就是说Spring Boot2.0的最低版本要求为JDK8,据了解国内大部分的互联网公司系统都还跑在JDK1.6/7 ...

  4. (转)Spring Boot 2(一):【重磅】Spring Boot 2.0权威发布

    http://www.ityouknow.com/springboot/2018/03/01/spring-boot-2.0.html 就在今天Spring Boot2.0.0.RELEASE正式发布 ...

  5. Spring Boot 2(一):Spring Boot 2.0新特性

    Spring Boot 2(一):Spring Boot 2.0新特性 Spring Boot依赖于Spring,而Spring Cloud又依赖于Spring Boot,因此Spring Boot2 ...

  6. spring boot 2.0(一)权威发布spring boot2.0

    Spring Boot2.0.0.RELEASE正式发布,在发布Spring Boot2.0的时候还出现一个小插曲,将Spring Boot2.0同步到Maven仓库的时候出现了错误,然后Spring ...

  7. Spring Boot 2(一):【重磅】Spring Boot 2.0权威发布

    就在今天Spring Boot2.0.0.RELEASE正式发布,今天早上在发布Spring Boot2.0的时候还出现一个小插曲,将Spring Boot2.0同步到Maven仓库的时候出现了错误, ...

  8. Spring Boot 非常好的学习资料

    from@https://gitee.com/didispace/SpringBoot-Learning Spring Boot 2.0 新特性学习 简介与概览 Spring Boot 2.0 正式发 ...

  9. spring boot学习01【搭建环境、创建第一个spring boot项目】

    1.给eclipse安装spring boot插件 Eclipse中安装Spring工具套件(STS): Help -> Eclipse Marketplace... 在Search标签或者Po ...

  10. Spring Boot (八): Mybatis 增强工具 MyBatis-Plus

    1. 简介 在上一篇文章<Spring Boot (七): Mybatis极简配置> 中我们介绍了在 Spring Boot 中 Mybatis 的基础使用方式,其中有一部分美中不足的是 ...

随机推荐

  1. windows 服务下搭建jsp运行环境

    此处搭建的是运行环境,不是开发环境. 1, 下载sdk 并安装  1.8      http://rj.baidu.com/soft/detail/14459.html?ald 2, 配置环境变量 步 ...

  2. vim 插入行号

    :let i=1000000|g/^/s//\=i.' '/|let i=i+1

  3. SQL server插入数据后,获取自增长字段的值

      ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 insert into Tb_People(uname,er ...

  4. ERROR:ORA-30076: 对析出来源无效的析出字段

    DEBUG:key: sql: select count(*) as col_0_0_ from jc_user cmsuser0_ where 1=1 and cmsuser0_.register_ ...

  5. 转:LPC2214的PLL与定时器设置

    原地址:http://blog.sina.com.cn/s/blog_4419d72d0100mu7h.html LPC2214的PLL与定时器设置 http://www.dpj365.cn/bbs/ ...

  6. devc++读取不了当前目录下的文件

    devc++在当前目录新建了一个文件之后,用文件读取的操作报错:     如图所示:           解决方案: 先把该文件从左侧工作空间中移除:       移除之后就没了:         再 ...

  7. 修改mysql字段类型,修改字段名

    修改字段类型(数据类型,长度,默认值) alter table user modify user_name 类型 修改字段名 方法一:alter table 表 change 旧字段名 新字段名 新数 ...

  8. 009-python一些问题整理

    1. Python中的 // 与 / 的区别 " / "  表示浮点数除法,返回浮点结果 >>> 90/30 3.0 " // " 表示整数除 ...

  9. springcloud:RPC和HTTP

    1.RPC和HTTP 无论是微服务还是SOA,都面临着服务间的远程调用.那么服务间的远程调用方式有哪些呢? 常见的远程调用方式有以下2种: RPC:Remote Produce Call远程过程调用, ...

  10. 禁止input文本框输入select无法选择

    readonly.disabled.autocomplete readonly表示此域的值不可修改,仅可与 type="text" 配合使用,可复制,可选择,可以接收焦点,后台会接 ...