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

ControllerAdvice的定义如下:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice {
/**
* Alias for the {@link #basePackages} attribute.
* <p>Allows for more concise annotation declarations e.g.:
* {@code @ControllerAdvice("org.my.pkg")} is equivalent to
* {@code @ControllerAdvice(basePackages="org.my.pkg")}.
* @since 4.0
* @see #basePackages()
*/
@AliasFor("basePackages")
String[] value() default {};
/**
* Array of base packages.
* <p>Controllers that belong to those base packages or sub-packages thereof
* will be included, e.g.: {@code @ControllerAdvice(basePackages="org.my.pkg")}
* or {@code @ControllerAdvice(basePackages={"org.my.pkg", "org.my.other.pkg"})}.
* <p>{@link #value} is an alias for this attribute, simply allowing for
* more concise use of the annotation.
* <p>Also consider using {@link #basePackageClasses()} as a type-safe
* alternative to String-based package names.
* @since 4.0
*/
@AliasFor("value")
String[] basePackages() default {};
/**
* Type-safe alternative to {@link #value()} for specifying the packages
* to select Controllers to be assisted by the {@code @ControllerAdvice}
* annotated class.
* <p>Consider creating a special no-op marker class or interface in each package
* that serves no purpose other than being referenced by this attribute.
* @since 4.0
*/
Class<?>[] basePackageClasses() default {};
/**
* Array of classes.
* <p>Controllers that are assignable to at least one of the given types
* will be assisted by the {@code @ControllerAdvice} annotated class.
* @since 4.0
*/
Class<?>[] assignableTypes() default {};
/**
* Array of annotations.
* <p>Controllers that are annotated with this/one of those annotation(s)
* will be assisted by the {@code @ControllerAdvice} annotated class.
* <p>Consider creating a special annotation or use a predefined one,
* like {@link RestController @RestController}.
* @since 4.0
*/
Class<? extends Annotation>[] annotations() default {};
}

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

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

下面给一个例子:

import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute; import com.gongren.dlg.activity.exception.NoSessionException; /**
* springMVC的ControllerAdvice
*
* @author yzl
* @see [相关类/方法](可选)
* @since [产品/模块版本] (可选)
*/
@ControllerAdvice
public class WebContextAdvice {
private static final Logger logger = LoggerFactory.getLogger(WebContextAdvice.class); /**
*
* 功能描述: <br>
* 应用上下文设值给Model对象
* 在jsp中使用:${ctx}
*
* @param request
* @return
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
@ModelAttribute(value="ctx")
public String setContextPath(HttpServletRequest request){
return request.getContextPath();
} /**
*
* 错误处理器
*
* @param e
* @return
* @see [相关类/方法](可选)
* @since [产品/模块版本](可选)
*/
@ExceptionHandler
public String handleIOException(HttpServletRequest request,HttpServletResponse response,Model model,Exception e) {
//请求类型,可以区分对待ajax和普通请求
String requestType = request.getHeader("X-Requested-With");
if(StringUtils.isNotBlank(requestType)){
//是ajax
try {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8"); PrintWriter writer = response.getWriter();
//具体操作
writer.write("json...");
//
writer.flush();
writer.close();
return null;
} catch (IOException e1) {
}
}
if(e instanceof NoSessionException){
logger.error("session超时,跳转到活动首页");
return "redirect:/mc/index";
}
logger.error("请求发生错误", e);
return "redirect:/mc/error";
}
}

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. Excel VBA自动添加证书

    ---恢复内容开始--- 在说这个话题之前,我先解释一下为什么要加数字证书签名,它有什么作用,后面再解释如何添加.首先解释下证书添加的位置,如下图所示: 1.单击左上角的Office 按钮,选择右下角 ...

  2. [SmartFoxServer概述]SFS2X协议

    SFS2X 客户端-服务器协议 SFS2X使用了一种高效的二进制协议,这种协议可以使服务器在各方面都表现出色.消息通过客户端和服务器引擎得到快速转换,在带宽上传输可更加轻便.附加的即时压缩,能够在不影 ...

  3. 条形码软件开发包Dynamic .NET TWAIN v5.0提供WPF功能

    Dynamsoft是一家著名的开发条形码控件开发包的公司,其旗下 Dynamic .NET TWAIN产品近日升级到v5.0版本,对于在支持WPF功能方面有着较大的改进.下面就让我们一起来看看这次更新 ...

  4. css三角形

    <html><head> <meta charset="UTF-8"></head><style> div{float: ...

  5. Android的项目不能直接引用可移植类库的项目解决方法

    深圳_exception() 10:25:51 Android的项目不能直接引用可移植类库的项目,但是可以引用可移植类库生成的dll,这就意味着无法直接断电调试可移植类库上海-黄药师() 10:26: ...

  6. elixir 高可用系列(三) GenEvent

    概述 GenEvent 是事件处理的通用部分的抽象. 通过 GenEvent ,我们给已有的服务 动态 的添加 事件处理. GenEevent 和 GenServer 的区别 之前已经介绍了 GenS ...

  7. 使用NHibernate(3)-- 用代码代替配置文件

    1,用代码配置Configure类. 上一篇“让代码跑起来”中,是通过在Web.config配置来实现Configure类的,NHibernate还提供了代码的方式. 把之前的配置都注释掉,然后修改A ...

  8. Unity3.0基于约定的自动注册机制

    前文<Unity2.0容器自动注册机制>中,介绍了如何在 Unity 2.0 版本中使用 Auto Registration 自动注册机制.在 Unity 3.0 版本中(2013年),新 ...

  9. google hack 之 查询语法

    google hack 之 查询语法 文/玄魂   前言 谷歌网页搜索技术,大部分在百度等搜索引擎中也适用.同样,这些搜索技术是来源于传统数据库检索技术,因而,对这部分的学习,能为后续章节的数据库检索 ...

  10. [MFC] MFC 仿 Flappy bird PC桌面版

    http://www.cr173.com/ 前些日子发现朋友都在玩flappy bird这款虐心的小游戏,网上也炒得很火,于是俺也想下一个玩玩.可是矮穷挫至今还没配上高端的智能机,于是去网上搜了一下, ...