@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. 居于集成了adt的Android 开发环境配置

    一.先说一下环境 Windows 8.1 64 位 注:win7 Ultimate  64 配置会出现 Android SDK manger 不能启动的问题,是因为android.bat 里调用了fi ...

  2. socket进阶

    socketserver(在Python2.*中的是SocketServer模块)是标准库中一个高级别的模块.用于简化网络客户与服务器的实现(在前面使用socket的过程中,我们先设置了socket的 ...

  3. 安装SQLSERVER2012遇到的一些问题

    安装SQLSERVER2012遇到的一些问题 先到MSDN我告诉你http://msdn.itellyou.cn/下载安装包,我每次都到MSDN我告诉你里下载的,因为那里的安装包保证能用 我的环境是: ...

  4. Python 拷贝对象(深拷贝deepcopy与浅拷贝copy)

    1. copy.copy 浅拷贝 只拷贝父对象,不会拷贝对象的内部的子对象. 2. copy.deepcopy 深拷贝 拷贝对象及其子对象 一个很好的例子: # -*-coding:utf-8 -*- ...

  5. Hyper-V的使用方法

    win8和win8.1以及win10自带虚拟机,无需再装第三方虚拟机软件. 首先需要在“启用或关闭windows功能”中,启用Hyper-V

  6. 基于OWIN WebAPI 使用OAuth授权服务【客户端验证授权(Resource Owner Password Credentials Grant)】

    适用范围 前面介绍了Client Credentials Grant ,只适合客户端的模式来使用,不涉及用户相关.而Resource Owner Password Credentials Grant模 ...

  7. hibernate date类型插入数据库时精度只到日期没有时间

    由hibernate 的逆向工具从数据库表生成的*.hbm.xml ,对于数据库的date类型生成如下:        <property name = "crttime"  ...

  8. [51单片机] SPI nRF24L01无线 [可以放在2个单片机里实现通信]

    main.c #include<reg51.h> #include"2401.h" #define uint unsigned int #define uchar un ...

  9. [stm32] 中断

    #include "stm32f10x.h" #include "stm32f10x_tim.h" #include "misc.h" #i ...

  10. intellij自动缩进排版

    用鼠标选中需要缩进的代码块,然后输入命令 ctrl+alt+i ref: http://stackoverflow.com/questions/12264127/how-to-reindent-lin ...