文章字数:311,阅读全文大约需要1分钟
注解ControllerAdvice
提供了controller的全局处理功能
@ExceptionHandler
:全局异常捕获,捕获到指定异常后处理。通常用作获取异常后统一返回结构化的错误信息
@InitBinder
:指定参数名,获取的参数绑定变量前的自定义操作,不如给时间日期增加解析器,构建不同的变量名头部信息。
@ModelAttribute
:该方法返回的值可以在controller中接收。
@ExceptionHandler
1 2 3 4 5 6 7 8
| @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ExceptionHandler { 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 { String[] value() default {}; }
|
- 指定转换器
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 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 { @AliasFor("name") String value() default ""; @AliasFor("value") String name() default ""; 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"; }
|