源码
@ControllerAdvice,是Spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强。让我们先看看@ControllerAdvice的实现:
package org.springframework.web.bind.annotation;
@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 {};
该注解使用@Component注解,这样的话当我们使用< context:component-scan>扫描时就能扫描到。
如果你的spring-mvc配置文件使用如下方式扫描bean
<context:component-scan base-package="com.sishuok.es" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
还需要把@ControllerAdvice包含进来,否则不起作用:
<context:component-scan base-package="com.sishuok.es" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>
用法
- 通过@ControllerAdvice注解可以将对于控制器的全局配置放在同一个位置。
- 注解了@ControllerAdvice的类的方法可以使用@ExceptionHandler、@InitBinder、@ModelAttribute注解到方法上。
- @ExceptionHandler:用于全局处理控制器里的异常。
- @InitBinder:用来设置WebDataBinder,用于自动绑定前台请求参数到Model中。
- @ModelAttribute:本来作用是绑定键值对到Model中,此处让全局的@RequestMapping都能获得在此处设置的键值对
- @ControllerAdvice注解将作用在所有注解了@RequestMapping的控制器的方法上。
实例
package org.lhzhian.base.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
/**
* 异常统一处理
* @author lhzhian
* @date 2016年4月28日
*/
@ControllerAdvice
public class GlobalExceptionHandler {
private final static String ERROR_PAGE = "error";
@ExceptionHandler(Exception.class)
public ModelAndView handle(Exception e){
ModelAndView mv = new ModelAndView();
mv.addObject("message", e.getMessage());
mv.setViewName(ERROR_PAGE);
return mv;
}
@ModelAttribute
//应用到所有@RequestMapping注解方法
//此处将键值对添加到全局,注解了@RequestMapping的方法都可以获得此键值对
public void addUser(Model model) {
model.addAttribute("msg", "此处将键值对添加到全局,注解了@RequestMapping的方法都可以获得此键值对");
}
@InitBinder
//应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器
//用来设置WebDataBinder,用于自动绑定前台请求参数到Model中。
public void initBinder(WebDataBinder binder) {
}
}
error页面
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>ERROR MESSAGE</h1>
<p>${message}</p>
</body>
</html>