@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. Subsets 子集系列问题 leetcode

    子集系列问题: Coding 问题中有时会出现这样的问题:给定一个集合,求出这个集合所有的子集(所谓子集,就是包含原集合中的一部分元素的集合). 或者求出满足一定要求的子集,比如子集中元素总和为定值, ...

  2. Divide Two Integers leetcode

    题目:Divide Two Integers Divide two integers without using multiplication, division and mod operator. ...

  3. [Leetcode][JAVA] Word Ladder II

    Given two words (start and end), and a dictionary, find all shortest transformation sequence(s) from ...

  4. Python成长笔记 - 基础篇 (五)

    1.装饰器: 装饰器:器代表函数的意思,装饰器就是一个函数,作用是用来装饰其他的函数 原则: 1.不能修改被装饰函数的源代码 2.不能修改被装饰函数的调用方式 实现装饰器所需要的知识: 1.函数即变量 ...

  5. phpcms后台登陆验证码不显示的解决方法

    方法一:检查主机环境,是否已经开启gd库.可以用探针,或者检查php.ini文件,搜索extension=php_gd2.dll,检查前面是否有注释符号,去掉即可. 方法二:检查配置文件是否正确.打开 ...

  6. Android简单图片浏览器

    效果如下:            代码编写如下: Crize_demo\app\src\main\res\layout\activity_main.xml <!--定义一个线性布局--> ...

  7. bzoj 3389

    题意:给定1维连续T<= 1000000个点,以及n<=10000个线段,求最少的线段覆盖该区间.. 思路:很显然,贪心是可以做的..不过这一题最有意思的是使可以转换为最短路模型.. 如果 ...

  8. 创建 kylin Module/Cube

    1. 首先要创建 Project 2. 再把Hive 表加载进来: 3. 创建model 3.1. 首先选择或者创建一个project   3.2.创建一个新modle   3.3. 选择数据库   ...

  9. C#的泛型委托与闭包函数

    前些天Wendy问我说Func<T, ResultT>是个什么意思,初学C#都觉得这样的写法很奇葩,甚至觉得这样写有点诡异,其实以我来看,这是体现C#函数式编程的又一个亮点. 从MSDN上 ...

  10. H5图片裁剪升级版(手机版)

    前段时间做了个跟裁剪相关的活动<用H5中的Canvas等技术制作海报>,这次公司要做个与奥运相关的活动,扫车牌赢奖. 于是我就在上一个活动的基础上,将代码重新封装一下,并且将计算方式写的更 ...