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

 

posted @ 2016-12-09 10:00  自行车上的程序员  阅读(11755)  评论(1编辑  收藏  举报