@ControllerAdvice是Spring 3.2新增的注解,主要是用来Controller的一些公共的需求的低侵入性增强提供辅助,作用于@RequestMapping标注的方法上。

ControllerAdvice的定义如下:

  1. @Target(ElementType.TYPE)
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Component
  5. public @interface ControllerAdvice {
  6. /**
  7. * Alias for the {@link #basePackages} attribute.
  8. * <p>Allows for more concise annotation declarations e.g.:
  9. * {@code @ControllerAdvice("org.my.pkg")} is equivalent to
  10. * {@code @ControllerAdvice(basePackages="org.my.pkg")}.
  11. * @since 4.0
  12. * @see #basePackages()
  13. */
  14. @AliasFor("basePackages")
  15. String[] value() default {};
  16. /**
  17. * Array of base packages.
  18. * <p>Controllers that belong to those base packages or sub-packages thereof
  19. * will be included, e.g.: {@code @ControllerAdvice(basePackages="org.my.pkg")}
  20. * or {@code @ControllerAdvice(basePackages={"org.my.pkg", "org.my.other.pkg"})}.
  21. * <p>{@link #value} is an alias for this attribute, simply allowing for
  22. * more concise use of the annotation.
  23. * <p>Also consider using {@link #basePackageClasses()} as a type-safe
  24. * alternative to String-based package names.
  25. * @since 4.0
  26. */
  27. @AliasFor("value")
  28. String[] basePackages() default {};
  29. /**
  30. * Type-safe alternative to {@link #value()} for specifying the packages
  31. * to select Controllers to be assisted by the {@code @ControllerAdvice}
  32. * annotated class.
  33. * <p>Consider creating a special no-op marker class or interface in each package
  34. * that serves no purpose other than being referenced by this attribute.
  35. * @since 4.0
  36. */
  37. Class<?>[] basePackageClasses() default {};
  38. /**
  39. * Array of classes.
  40. * <p>Controllers that are assignable to at least one of the given types
  41. * will be assisted by the {@code @ControllerAdvice} annotated class.
  42. * @since 4.0
  43. */
  44. Class<?>[] assignableTypes() default {};
  45. /**
  46. * Array of annotations.
  47. * <p>Controllers that are annotated with this/one of those annotation(s)
  48. * will be assisted by the {@code @ControllerAdvice} annotated class.
  49. * <p>Consider creating a special annotation or use a predefined one,
  50. * like {@link RestController @RestController}.
  51. * @since 4.0
  52. */
  53. Class<? extends Annotation>[] annotations() default {};
  54. }

和此注解配合使用的其他注解有:

  1. @ExceptionHandler   自定义的错误处理器
  2. @ModelAttribute      全局的对所有的controller的Model添加属性
  3. @InitBinder  对表单数据绑定

下面给一个例子:

  1. import java.io.IOException;
  2. import java.io.PrintWriter;
  3.  
  4. import javax.servlet.http.HttpServletRequest;
  5. import javax.servlet.http.HttpServletResponse;
  6.  
  7. import org.apache.commons.lang.StringUtils;
  8. import org.slf4j.Logger;
  9. import org.slf4j.LoggerFactory;
  10. import org.springframework.ui.Model;
  11. import org.springframework.web.bind.annotation.ControllerAdvice;
  12. import org.springframework.web.bind.annotation.ExceptionHandler;
  13. import org.springframework.web.bind.annotation.ModelAttribute;
  14.  
  15. import com.gongren.dlg.activity.exception.NoSessionException;
  16.  
  17. /**
  18. * springMVC的ControllerAdvice
  19. *
  20. * @author yzl
  21. * @see [相关类/方法](可选)
  22. * @since [产品/模块版本] (可选)
  23. */
  24. @ControllerAdvice
  25. public class WebContextAdvice {
  26. private static final Logger logger = LoggerFactory.getLogger(WebContextAdvice.class);
  27.  
  28. /**
  29. *
  30. * 功能描述: <br>
  31. * 应用上下文设值给Model对象
  32. * 在jsp中使用:${ctx}
  33. *
  34. * @param request
  35. * @return
  36. * @see [相关类/方法](可选)
  37. * @since [产品/模块版本](可选)
  38. */
  39. @ModelAttribute(value="ctx")
  40. public String setContextPath(HttpServletRequest request){
  41. return request.getContextPath();
  42. }
  43.  
  44. /**
  45. *
  46. * 错误处理器
  47. *
  48. * @param e
  49. * @return
  50. * @see [相关类/方法](可选)
  51. * @since [产品/模块版本](可选)
  52. */
  53. @ExceptionHandler
  54. public String handleIOException(HttpServletRequest request,HttpServletResponse response,Model model,Exception e) {
  55. //请求类型,可以区分对待ajax和普通请求
  56. String requestType = request.getHeader("X-Requested-With");
  57. if(StringUtils.isNotBlank(requestType)){
  58. //是ajax
  59. try {
  60. response.setCharacterEncoding("UTF-8");
  61. response.setContentType("application/json; charset=utf-8");
  62.  
  63. PrintWriter writer = response.getWriter();
  64. //具体操作
  65. writer.write("json...");
  66. //
  67. writer.flush();
  68. writer.close();
  69. return null;
  70. } catch (IOException e1) {
  71. }
  72. }
  73. if(e instanceof NoSessionException){
  74. logger.error("session超时,跳转到活动首页");
  75. return "redirect:/mc/index";
  76. }
  77. logger.error("请求发生错误", e);
  78. return "redirect:/mc/error";
  79. }
  80. }

spring之ControllerAdvice注解的更多相关文章

  1. spring的@ControllerAdvice注解

    @ControllerAdvice注解是Spring3.2中新增的注解,学名是Controller增强器,作用是给Controller控制器添加统一的操作或处理. 对于@ControllerAdvic ...

  2. Spring的ControllerAdvice注解

    @ControllerAdvice,是spring3.2提供的新注解,其实现如下所示: @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUN ...

  3. spring mvc异常统一处理(ControllerAdvice注解)

    首先我的项目是一个为移动端提供的json数据的,当后台报错时如果为移动端返回一个错误页面显得非常不友好,于是通过ControllerAdvice注解返回json数据. 首先创建一个异常处理类: pac ...

  4. Spring boot异常统一处理方法:@ControllerAdvice注解的使用、全局异常捕获、自定义异常捕获

    一.全局异常 1.首先创建异常处理包和类 2.使用@ControllerAdvice注解,全局捕获异常类,只要作用在@RequestMapping上,所有的异常都会被捕获 package com.ex ...

  5. Spring MVC Framework 注解

    ControllerAdvice Spring MVC Framework会把 @ControllerAdvice注解内部使用 @ExceptionHandler.@InitBinder.@Model ...

  6. Spring Boot常用注解总结

    Spring Boot常用注解总结 @RestController和@RequestMapping注解 @RestController注解,它继承自@Controller注解.4.0之前的版本,Spr ...

  7. SpringMVC 中 @ControllerAdvice 注解的三种使用场景!

    @ControllerAdvice ,很多初学者可能都没有听说过这个注解,实际上,这是一个非常有用的注解,顾名思义,这是一个增强的 Controller.使用这个 Controller ,可以实现三个 ...

  8. Spring Boot @ControllerAdvice 处理全局异常,返回固定格式Json

    需求 在构建RestFul的今天,我们一般会限定好返回数据的格式比如: { "code": 0,  "data": {},  "msg": ...

  9. spring 、spring boot 常用注解

    @Profile 1.用户配置文件注解. 2.使用范围: @Configration 和 @Component 注解的类及其方法, 其中包括继承了 @Component 的注解: @Service. ...

随机推荐

  1. Matlab神经网络函数newff()新旧用法差异

    摘要 在Matlab R2010a版中,如果要创建一个具有两个隐含层.且神经元数分别为5.3的前向BP网络,使用旧的语法可以这样写: net1 = newff(minmax(P), [5 3 1]); ...

  2. .android:allowTaskReparenting 等Activity 的task属性

    转自http://blog.csdn.net/javayinjaibo/article/details/8855678 1.android:allowTaskReparenting 这个属性用来标记一 ...

  3. C2第四次作业解题报告

    看过题解后如果觉得还算有用,请帮忙加点我所在团队博客访问量 http://www.cnblogs.com/newbe/ http://www.cnblogs.com/newbe/p/4069834.h ...

  4. 使用 New Relic 监控接口服务性能

    偶然看到贴子在使用[Rails API] 使用这个APM监控,今天试了下.NET IIS环境下,配置一路NEXT即可. 主要指标 服务响应时间 Segment SQL执行时间 安全问题 1.走HTTP ...

  5. Dos脚本判断文件大小

    @echo off & setlocal EnableDelayedExpansion del 1.txt /q del 2.txt /q for /f %%i in (*) do (echo ...

  6. [游戏模版12] Win32 稳定定时

    >_<:The last time,we learned how to use timer to make the picture run and change show,but some ...

  7. Firefox SVG getBBox方法返回'NS_ERROR_FAILURE'错误分析

    在SVG中,我们无法给Text元素设置Width和Height属性,因此无法直接获取Text元素的高和宽.如果想要给Text元素添加背景色,最简单的办法就是在Text元素的下面添加Rect,然后给Re ...

  8. [BTS] MSDTC

    A message sent to adapter "WCF-SQL" on send port "SP.TMS.InsertDataToDB.WCFSQL" ...

  9. 自制操作系统(二) 让bootsector开机启动打印一首诗

    qq:992591601 欢迎交流 2016-03-31作 2016-06-01.2016-06-27改 我总结了些基本原理: 1.软盘的第一个扇区为启动区 2.计算机读软盘是以512字节为单位来读写 ...

  10. 构建单页Web应用

    摘自前端农民工的博客 让我们先来看几个网站: coding teambition cloud9 注意这几个网站的相同点,那就是在浏览器中,做了原先“应当”在客户端做的事情.它们的界面切换非常流畅,响应 ...