SpringMVC重要注解 @ControllerAdvice
@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>扫描时也能扫描到。
再一起看看官方提供的comment。
大致意思是:
@ControllerAdvice是一个@Component,用于定义@ExceptionHandler,@InitBinder和@ModelAttribute方法,适用于所有使用@RequestMapping方法。Spring4之前,
@ControllerAdvice在同一调度的Servlet中协助所有控制器。Spring4已经改变:@ControllerAdvice支持配置控制器的子集,而默认的行为仍然可以利用。在Spring4中,
@ControllerAdvice通过annotations(),basePackageClasses(),basePackages()方法定制用于选择控制器子集。
不过据经验之谈,只有配合@ExceptionHandler最有用,其它两个不常用。
在SpringMVC重要注解(一)@ExceptionHandler和@ResponseStatus我们提到,如果单使用@ExceptionHandler,只能在当前Controller中处理异常。但当配合@ControllerAdvice一起使用的时候,就可以摆脱那个限制了。
package com.somnus.advice; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody; @ControllerAdvice
public class ExceptionAdvice { @ExceptionHandler({ ArrayIndexOutOfBoundsException.class })
@ResponseBody
public String handleArrayIndexOutOfBoundsException(Exception e) {
e.printStackTrace();
return "testArrayIndexOutOfBoundsException";
@Controller
@RequestMapping(value = "exception")
public class ExceptionHandlerController { @RequestMapping(value = "e2/{id}", method = { RequestMethod.GET })
@ResponseBody
public String testExceptionHandle2(@PathVariable(value = "id") Integer id) {
List<String> list = Arrays.asList(new String[]{"a","b","c","d"});
return list.get(id-1);
} }
当我们访问http://localhost:8080/SpringMVC/exception/e2/5的时候会抛出ArrayIndexOutOfBoundsException异常,这时候定义在@ControllerAdvice中的@ExceptionHandler就开始发挥作用了。
如果我们想定义一个处理全局的异常
package com.somnus.advice;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class ExceptionAdvice {
@ExceptionHandler({ Exception.class })
@ResponseBody
public String handException(HttpServletRequest request ,Exception e) throws Exception {
e.printStackTrace();
return e.getMessage();
}
}
乍一眼看上去毫无问题,但这里有一个纰漏,由于Exception是异常的父类,如果你的项目中出现过在自定义异常中使用@ResponseStatus的情况,你的初衷是碰到那个自定义异常响应对应的状态码,而这个控制器增强处理类,会首先进入,并直接返回,不会再有@ResponseStatus的事情了,这里为了解决这种纰漏,我提供了一种解决方式。
package com.somnus.advice;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class ExceptionAdvice {
@ExceptionHandler({ Exception.class })
@ResponseBody
public String handException(HttpServletRequest request ,Exception e) throws Exception {
e.printStackTrace();
//If the exception is annotated with @ResponseStatus rethrow it and let
// the framework handle it - like the OrderNotFoundException example
// at the start of this post.
// AnnotationUtils is a Spring Framework utility class.
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
throw e;
}
// Otherwise setup and send the user to a default error-view.
/*ModelAndView mav = new ModelAndView();
mav.addObject("exception", e);
mav.addObject("url", request.getRequestURL());
mav.setViewName(DEFAULT_ERROR_VIEW);
return mav;*/
return e.getMessage();
}
}
如果碰到了某个自定义异常加上了@ResponseStatus,就继续抛出,这样就不会让自定义异常失去加上@ResponseStatus的初衷。
SpringMVC重要注解 @ControllerAdvice的更多相关文章
- SpringMVC异常处理注解@ExceptionHandler@ControllerAdvice@ResponseStatus
参考: http://blog.csdn.net/w372426096/article/details/78429132 http://blog.csdn.net/w372426096/article ...
- Spring3.2新注解@ControllerAdvice
Spring3.2新注解@ControllerAdvice @ControllerAdvice,是spring3.2提供的新注解,从名字上可以看出大体意思是控制器增强.让我们先看看@Control ...
- springBoot注解大全JPA注解springMVC相关注解全局异常处理
https://www.cnblogs.com/tanwei81/p/6814022.html 一.注解(annotations)列表 @SpringBootApplication:包含了@Compo ...
- Spring 和 SpringMVC 常用注解和配置(@Autowired、@Resource、@Component、@Repository、@Service、@Controller的区别)
Spring 常用注解 总结内容 一.Spring部分 1.声明bean的注解 2.注入bean的注解 3.java配置类相关注解 4.切面(AOP)相关注解 5.事务注解 6.@Bean的属性支持 ...
- SpringMVC常用注解實例詳解3:@ResponseBody
我的開發環境框架: springmvc+spring+freemarker開發工具: springsource-tool-suite-2.9.0JDK版本: 1.6.0_29tomcat ...
- SpringMVC常用注解實例詳解2:@ModelAttribute
我的開發環境框架: springmvc+spring+freemarker開發工具: springsource-tool-suite-2.9.0JDK版本: 1.6.0_29tomcat ...
- springMVC的注解详解
springmvc常用注解标签详解 1.@Controller 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业 ...
- springmvc常用注解与类型转换
springmvc常用注解与类型转换 一:前置 spring -servlet.xml 注入 <!-- 启用spring mvc 注解 --> <context:annotation ...
- springMvc的注解注入方式
springMvc的注解注入方式 最近在看springMvc的源码,看到了该框架的注入注解的部分觉的有点吃力,可能还是对注解的方面的知识还认识的不够深刻,所以特意去学习注解方面的知识.由于本人也是抱着 ...
随机推荐
- X264-编码模块和NAL打包输出
在上一篇介绍了编码器的VCL编码操作,分析了函数x264_slice_write().函数x264_slice_write()里有四个关键模块,分别是宏块分析模块.宏块编码模块.熵编码模块和滤波模块, ...
- 6、Routing
Routing In the previous tutorial we built a simple logging system. We were able to broadcast log mes ...
- URL 路由系统 + views 函数
一.URL URL配置(URLconf)就像Django 所支撑网站的目录.它的本质是URL模式以及要为该URL模式调用的视图函数之间的映射表:你就是以这种方式告诉Django,对于这个URL调用这段 ...
- Nginx类
nginx常见错误页面有哪些?对于其解决方法是什么? 404 bad request 请求失败,请求所希望得到的资源未被在服务器上发现.没有信息能够告诉用户这个状况到底是暂时的还是永久的.假如服务器知 ...
- 非root用户安装、配置mysql
1. 下载mysql,可能是因为服务器操作系统版本较低(CentOS4.3),安装5.7时提示缺lib,刚好我不需要一定安装新版,所以下载了5.1 Linux - Generic (glibc 2.5 ...
- 青春正盛,未来可期。马上2020了,低成本投资自己:vip测试提升圈
应部分群友再三强烈建议要求,组建了一个测试提升小分队,相约vip测试提升圈, 这里汇集了一群热爱学习.渴望提升的测试小伙伴,大家都朝着自己的梦想拼命努力: 此圈将助你在接口自动化和性能方向全面提升,提 ...
- 页面元素定位及操作--xpath
简介: 在 XPath 中,有七种类型的节点:元素.属性.文本.命名空间.处理指令.注释以及文档(根)节点.XML 文档是被作为节点树来对待的.树的根被称为文档节点或者根节点. /xxx 页面输出 / ...
- python字符串连接的三种方法
1.+号连接 a="hello," b="world!" c=a+b print(c) 有一点需要注意的是,字符串类型是不可变的,所以每一次应用加号连接字符串都 ...
- Excel 文本函数
1.FIND函数--要查找的字符在 字符串中 的 位置 FIND(find_text,within_text,start_num) Find_text 是要查找的字符串. Within_text 是 ...
- stringstream字符串流的妙用
现在有一个数组,其值为从1到10000的连续增长的数字.出于某次偶然操作,导致这个数组中丢失了某三个元素,同时顺序被打乱,现在需要你用最快的方法找出丢失的这三个元素,并且将这三个元素根据从小到大重新拼 ...