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. ...
随机推荐
- Python爬虫(一) 信息系统集成及服务资质网
警告:不要恶意的访问网站,仅供学习使用! 本教程实例只抓取信息系统集成及服务资质网的企业资质查询. 1. 抓包 打开谷歌浏览器的开发者工具并访问该网站,过滤请求后找到请求数据的包. 1.1 找到相应封 ...
- office2003-2007 绿色版 出错 文件丢失(未解决)
- 这个版本是我大学时候(2012)年一直用到现在的版本:目录结构如下: 原来一直在32位系统中使用,没有出错过; - 刚装的两台电脑系统分别为 Win7Pro 和 Win10Pro ,都是64位的: ...
- java后台开发传输乱码&&接口post传参失败
起因: 前几天遇到的问题,才有时间记录,需求:本地生成xml形式的字符串以参数形式用post方法传送到对方的固定接口: 这个需求写的时候感觉很容易,本地测试的时候,也觉得很简单就过了,然后和对方联调的 ...
- Frugalware Linux 1.9 RC1 发布
Frugalware Linux 1.9 RC1 发布了,下载地址:fvbe-1.9rc1-full-x86_64.iso (1,874MB, SHA1). 发行通知:http://www.fruga ...
- 一步一步搭建客服系统 (6) chrome桌面共享
本文介绍了如何在chrome下用webrtc来实现桌面共.因为必要要用https来访问才行,因此也顺带介绍了如何使用SSL证书. 1 chrome扩展程序 先下载扩展程序示例: https://git ...
- 【Leetcode】【Medium】word search
Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from l ...
- 【ASP.NET Web API教程】6.2 ASP.NET Web API中的JSON和XML序列化
谨以此文感谢关注此系列文章的园友!前段时间本以为此系列文章已没多少人关注,而不打算继续下去了.因为文章贴出来之后,看的人似乎不多,也很少有人对这些文章发表评论,而且几乎无人给予“推荐”.但前几天有人询 ...
- easyui使用技巧
1.自定义datagrid字体大小 通过formatter改变字体大小,然后在列中使用: 如下: function formatFontSize(value){ return'<span sty ...
- JUnit 测试
Junit 使用 1.忽略测试方法.在使用@Test的方法上使用@Ignore,将不会对此方法进行测试 2.测试套件 解决的问题: 1.对测试类进行统一测试,而不必在单独测试类上一个一个进行测试. 使 ...
- JavaScript text highlighting JQuery plugin
介绍一个JQuery的插件,用来在页面上高亮显示匹配到的字符串. Demo 点击下面的两个链接以查看效果: highlight javascript 点击Remove highlights移除高亮显示 ...