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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM