spring之ControllerAdvice注解
@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 {};
}
和此注解配合使用的其他注解有:
- @ExceptionHandler 自定义的错误处理器
- @ModelAttribute 全局的对所有的controller的Model添加属性
- @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注解的更多相关文章
- spring的@ControllerAdvice注解
@ControllerAdvice注解是Spring3.2中新增的注解,学名是Controller增强器,作用是给Controller控制器添加统一的操作或处理. 对于@ControllerAdvic ...
- Spring的ControllerAdvice注解
@ControllerAdvice,是spring3.2提供的新注解,其实现如下所示: @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUN ...
- spring mvc异常统一处理(ControllerAdvice注解)
首先我的项目是一个为移动端提供的json数据的,当后台报错时如果为移动端返回一个错误页面显得非常不友好,于是通过ControllerAdvice注解返回json数据. 首先创建一个异常处理类: pac ...
- Spring boot异常统一处理方法:@ControllerAdvice注解的使用、全局异常捕获、自定义异常捕获
一.全局异常 1.首先创建异常处理包和类 2.使用@ControllerAdvice注解,全局捕获异常类,只要作用在@RequestMapping上,所有的异常都会被捕获 package com.ex ...
- Spring MVC Framework 注解
ControllerAdvice Spring MVC Framework会把 @ControllerAdvice注解内部使用 @ExceptionHandler.@InitBinder.@Model ...
- Spring Boot常用注解总结
Spring Boot常用注解总结 @RestController和@RequestMapping注解 @RestController注解,它继承自@Controller注解.4.0之前的版本,Spr ...
- SpringMVC 中 @ControllerAdvice 注解的三种使用场景!
@ControllerAdvice ,很多初学者可能都没有听说过这个注解,实际上,这是一个非常有用的注解,顾名思义,这是一个增强的 Controller.使用这个 Controller ,可以实现三个 ...
- Spring Boot @ControllerAdvice 处理全局异常,返回固定格式Json
需求 在构建RestFul的今天,我们一般会限定好返回数据的格式比如: { "code": 0, "data": {}, "msg": ...
- spring 、spring boot 常用注解
@Profile 1.用户配置文件注解. 2.使用范围: @Configration 和 @Component 注解的类及其方法, 其中包括继承了 @Component 的注解: @Service. ...
随机推荐
- C2第七次作业解题报告
看过题解后如果觉得还算有用,请帮忙加点我所在团队博客访问量 http://www.cnblogs.com/newbe/ http://www.cnblogs.com/newbe/p/4069834.h ...
- Semantic-UI和其他几个前端框架
本来是想介绍Semantic-UI的,但如果只介绍这个框架,没什么内容,框架相关feature站点上有不需要说,所以干脆列出自己常用的几个前端框架,算是做个阶段性总结. 本文的核心是侧重于HTML/C ...
- 配置本地IIS和VS自带IIS
以前调试网站一直用的vs自带的IIS,做为学习没啥大碍,但要是用于团队项目开发就会带来诸多不便.团队开发项目有统一的网站端口号.文件目录什么的,端口号可以在配置文件中修改倒也没啥,但是要在自己的项目中 ...
- ASP.NET MVC学习之模型验证篇
一.学习前的一句话 在这里要先感谢那些能够点开我随笔的博友们.慢慢的已经在博客园中度过一年半了,伊始只是将博客园作为自己学习的记录本一样使用,也不敢将自己的随笔发表到博客园首页,生怕自己的技艺不高,反 ...
- C#设计模式(14)——模板方法模式(Template Method)
一.引言 提到模板,大家肯定不免想到生活中的“简历模板”.“论文模板”.“Word中模版文件”等,在现实生活中,模板的概念就是——有一个规定的格式,然后每个人都可以根据自己的需求或情况去更新它,例如简 ...
- JavaScript严谨模式(Strict Mode)
下面的内容翻译自It’s time to start using JavaScript strict mode,作者Nicholas C.Zakas参与了YUI框架的开发,并撰写了多本前端技术书籍,在 ...
- 在Eclipse添加Android兼容包( v4、v7 appcompat )
昨天添加Android兼容包,碰到了很多问题,在这里记录一下,让后面的路好走. 如何选择兼容包, 请参考Android Support Library Features(二) 一.下载Support ...
- JavaScript this 总结(含 ES6)
本文主要总结自<JavaScript 语言精粹>.部分总结自<JavaScript 高级程序设计>以及自己的经验 四种调用模式 在 JavaScript 中,this 的值取决 ...
- MySQL笔记汇总
[目录] MySQL笔记汇总 一.mysql简介 数据简介 结构化查询语言 二.mysql命令行操作 三.数据库(表)更改 表相关 字段相关 索引相关 表引擎操作 四.数据库类型 数字型 字符串型 日 ...
- atitit.跨平台gui 概览
atitit.跨平台gui 概览 为什么需要跨平台gui 国际上那些跨平台的GUI程序,除了像Firefox之类的大型项目会重写界面外,中小型的项目基本上都是用GTK+或WxWidgets为多.毕竟要 ...