1. 程式人生 > >spring之ControllerAdvice註解

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 {}; }

和此註解配合使用的其他註解有:

  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";
    }
}

相關推薦

springControllerAdvice註解

@ControllerAdvice是Spring 3.2新增的註解,主要是用來Controller的一些公共的需求的低侵入性增強提供輔助,作用於@RequestMapping標註的方法上。 ControllerAdvice的定義如下: @Target(ElementType.TYPE) @Retention

Spring Enable* 註解的工作原理

    通過簡單的@Enable* 來開啟一項功能的支援,從而避免自己配置大量的程式碼降低使用的難度. 通過觀察@Enable*註解的原始碼,發現所有的註解都有一個@Import註解,它是用來匯入配置類的,這也就意味著這些自動開啟的實現其實是匯入了一些自動配置的 bean,

Spring 條件註解

      根據條件註解 @Conditional  在不同條件下建立不同的 bean. 判斷條件定義: package com.pangu.conditional; import org.springframework.context.an

Spring快取註解@Cacheable

https://www.cnblogs.com/fashflying/p/6908028.html   從3.1開始,Spring引入了對Cache的支援。其使用方法和原理都類似於Spring對事務管理的支援。Spring Cache是作用在方法上的,其核心思想是這樣的:當我們在呼叫一個快取方法

Spring條件註解@Conditional,條件(系統)不同注入的物件也不同。

條件註解,可以根據不同的條件來做出不同的事情。在Spring中條件註解可以說是設計模式中狀態模式的一種體現方式,同時也是面向物件程式設計中多型的應用部分。 在Spring框架中,當我們使用條件註解時,我們會為每種獨立的條件建立一個類,根據這個類對應的條件的成立

Spring@ConfigurationProperties註解

@ConfigurationProperties的使用方式有兩種: 在類上使用 在工廠方法上使用該註解,和@Bean一起使用 1.在類上使用: 建立一個People實體類: package com.config.server.endpoint; publ

spring的@ControllerAdvice註解

可能 aop back tco fcc ron doc 統一 接口 @ControllerAdvice註解是Spring3.2中新增的註解,學名是Controller增強器,作用是給Controller控制器添加統一的操作或處理。 對於@ControllerAdvice,

SpringFrameworkControllerAdvice註解的原始碼分析

    SpringFramework版本5.0.9.release。     我們會通

spring通過註解方式配置Bean(一)

(1)元件掃描:spring能夠從classpath下自動掃描、偵測和例項化具有特定註解的元件。 (2)特定元件包括: @Component:基本註解,標識一個受spring管理的元件; @Respority:標識持久層元件; @Service:標識服務層(業務層)元件; @Controller:標識表現層

Spring Boot annotation註解

頁面 osi 數據 加載 依賴註入 bsp 類型 數據庫 聲明 一:基於類的註解:(1)初始裝載@SpringBootApplication spring-boot程序入口標誌類@Configuration

spring註解(一)概述

dsm 的人 src article service 優缺點 中一 auto 數據 Spring的核心是依賴註入(DI),而依賴註入的基礎是依賴信息的配置。這些配置稱之為元數據。在之前的的學習中。一直採用的是基於xml的配置,這些元數據配置在spring內部被註冊成為B

Spring框架第四篇基於註解的DI註入

聯合 junit4 style troy ont student stc 創建配置文件 int 一、說明 [email protected]/* */,但意義不同的註解還有三個: 1)@Repository:註解在Dao實現類上 2)@Service:註解

SpringAOP的註解配置

函數 cts expr pro text bsp 定義 一個 rod 配置過程可以簡單的分為3步: 1,業務類配置 在業務類前加入,將業務類交由Spring管理 @Component("s") 這個表示,這個業務類的Bean名字為 s 。 2,將切點和切面

spring boot框架學習學前掌握重要註解(1)-java配置方式

spring boot   本節主要內容:  1:重點註解介紹  2:使用重點註解環境搭建  聲明:  本文是《凱哥陪你學系列-框架學習之spring boot框架學習》中學前掌握之重要註解(1)  java配置是spring 4.x推薦的撇嘴方式。可以完全代替xml配置。  1:重點註解  @con

spring boot框架學習重要註解3註解方式讀取外部資源配置文件

凱哥java java註解 本節主要內容:1:是用非註解方式怎麽獲取配置文件中的配置項2:使用註解實戰獲取外部properties文件配置項聲明:本文是《凱哥陪你學系列-框架學習之spring boot框架學習》中spring boot框架學習學前掌握之重要註解(3)-通過註解方式讀取外部資源配置文件

spring boot框架學習學前掌握重要註解(4)-通過註解方式讀取外部資源配置文件2

spring boot kaigejava 凱哥java本節主要內容:1:思考問題:怎麽讀取多個配置文件,如果文件不存在怎麽辦2:配置數據庫連接池聲明:本文是《凱哥陪你學系列-框架學習之spring boot框架學習》中spring boot框架學習學前掌握之重要註解(4)-通過註解方式讀取外部資源配置文件2

spring boot框架學習學前掌握重要註解(2)-通過java的配置方式進行配置spring

凱哥java kaigejava本節主要內容:1:通過代碼演示實現零XML配置spring2:使用重點註解理解聲明:本文是《凱哥陪你學系列-框架學習之spring boot框架學習》中spring boot框架學習學前掌握之重要註解(2)-通過java的配置方式進行配置spring.在上一節《spring b

Spring基礎知識基於註解的AOP

sdn 相互 com 目的 declare 裝配bean 四種 ace 裝配 背景概念:   1)橫切關註點:散布在應用中多處的功能稱為橫切關註點   2)通知(Advice):切面完成的工作。通知定了了切面是什麽及何時調用。     5中可以應用的通知:         

Java 系列spring學習--springmvc註解方式(五)

internal fault .org blank port imp handle scan html 一、springmvc註解方式   註解方式使用的更多,更加靈活。在上一篇的博客的基礎上修改springmvc-servlet.xml配置文件。 <?xml ve

Spring框架 @Valid註解的使用(嵌套類型的效驗)

Springboot 之@Valid註解@Valid註解可以實現數據的驗證,你可以定義實體,在實體的屬性上添加校驗規則,而在API接收數據時添加@valid關鍵字,這時你的實體將會開啟一個校驗的功能。@Valid 註解類型的使用:@Null限制只能為null@NotNull限制必須不為null@AssertF