0%

ControllerAdvice增强器

文章字数:311,阅读全文大约需要1分钟

注解ControllerAdvice提供了controller的全局处理功能

  1. @ExceptionHandler:全局异常捕获,捕获到指定异常后处理。通常用作获取异常后统一返回结构化的错误信息

  2. @InitBinder:指定参数名,获取的参数绑定变量前的自定义操作,不如给时间日期增加解析器,构建不同的变量名头部信息。

  3. @ModelAttribute:该方法返回的值可以在controller中接收。

@ExceptionHandler

1
2
3
4
5
6
7
8

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ExceptionHandler {
// 指定需要捕获的异常的Class类型
Class<? extends Throwable>[] value() default {};
}
1
2
3
4
5
6
7
8
9
@ControllerAdvice(basePackages = "mvc")
public class SpringControllerAdvice {
//捕捉到异常后返回异常界面
@ExceptionHandler(RuntimeException.class)
public ModelAndView runtimeException(RuntimeException e) {
e.printStackTrace();
return new ModelAndView("error");
}
}

@InitBinder

作用于通过@RequestParam,@RequestBody或者@ModelAttribute等注解绑定的参数

1
2
3
4
5
6
7
8
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface InitBinder {
// 这里value参数用于指定需要绑定的参数名称,如果不指定,则会对所有的参数进行适配,
// 只有是其指定的类型的参数才会被转换
String[] value() default {};
}
  1. 指定转换器
1
2
3
4
5
6
7
8

@ControllerAdvice(basePackages = "mvc")
public class SpringControllerAdvice {
@InitBinder
public void globalInitBinder(WebDataBinder binder) {
binder.addCustomFormatter(new DateFormatter("yyyy-MM-dd"));
}
}
  1. 不同的前缀返回给不同的对象
1
2
3
4
5
6
7
8
9
10
11
12
controller:
@InitBinder(“student”)
public void initUser(WebDataBinder binder){
binder.setFieldDefaultPrefix(“student”)
}
@InitBinder(“teacher”)
public void initAdmin(WebDataBinder binder){
binder.setFieldDefaultPrefix(“teacher”);
}
@RequestMapping("/xx")
… save(Teacher teacher,Student student){
}

@ModelAttribute

接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ModelAttribute {

// 该属性与name属性的作用一致,用于指定目标参数的名称
@AliasFor("name")
String value() default "";

@AliasFor("value")
String name() default "";

// 与name属性一起使用,如果指定了binding为false,那么name属性指定名称的属性将不会被处理
boolean binding() default true;
}

使用:

1
2
3
4
5
6
7
@ControllerAdvice(basePackages = "mvc")
public class SpringControllerAdvice {
@ModelAttribute(value = "message")
public String globalModelAttribute() {
return "valuexxxx";
}
}
1
2
3
4
5
6
@RequestMapping(value = "/demo")
public ModelAndView detail(@ModelAttribute("message") String message) {
//获取到了
System.out.println(message);
return "ok";
}