博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring之ControllerAdvice注解
阅读量:4947 次
发布时间:2019-06-11

本文共 4632 字,大约阅读时间需要 15 分钟。

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

ControllerAdvice的定义如下:

@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Componentpublic @interface ControllerAdvice {    /**     * Alias for the {
@link #basePackages} attribute. *

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. *

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"})}. *

{

@link #value} is an alias for this attribute, simply allowing for * more concise use of the annotation. *

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. *

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. *

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. *

Controllers that are annotated with this/one of those annotation(s) * will be assisted by the {

@code @ControllerAdvice} annotated class. *

Consider creating a special annotation or use a predefined one, * like {

@link RestController @RestController}. * @since 4.0 */ Class
[] 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 [产品/模块版本] (可选) */@ControllerAdvicepublic class WebContextAdvice {    private static final Logger logger = LoggerFactory.getLogger(WebContextAdvice.class);        /**     *      * 功能描述: 
* 应用上下文设值给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"; }}

 

转载于:https://www.cnblogs.com/yangzhilong/p/6148309.html

你可能感兴趣的文章
页面加载骨架
查看>>
关于android系统不关屏设置
查看>>
SONY VPCS138EC降级安装XP
查看>>
[luogu4201][bzoj1063]设计路线【树形DP】
查看>>
手机抓包-手机劫持域名到指定服务器
查看>>
被放逐的皇后 金建云
查看>>
Javascript 有用参考函数
查看>>
点群的判别(三)
查看>>
gradle
查看>>
GNSS 使用DFT算法 能量损耗仿真
查看>>
常见的控制跳转的宏定义
查看>>
JavaSE| 面向对象的三大特征
查看>>
tensorflow Tensorboard可视化-【老鱼学tensorflow】
查看>>
eigen主页
查看>>
暑假周进度报告1
查看>>
兔子数
查看>>
网页抓取 总结
查看>>
移动端自适应适配布局
查看>>
【vue】vue中v-charts的使用
查看>>
PropertiesConfiguration读取值中包含英文逗号,用“\”转义
查看>>