浅谈对ControllerAdvice注解的理解

  该注解顾名思义增强器,对注解了Controller类的增强,@ControllerAdvice的实现:

/**
 * Specialization of {@link Component @Component} for classes that declare
 * {@link ExceptionHandler @ExceptionHandler}, {@link InitBinder @InitBinder}, or
 * {@link ModelAttribute @ModelAttribute} methods to be shared across
 * multiple {@code @Controller} classes.
 *
 
 * performance and add complexity.
 *
 * @author Rossen Stoyanchev
 * @author Brian Clozel
 * @author Sam Brannen
 * @since 3.2
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface ControllerAdvice {

部分源码,该注解使用@Component注解,这样的话当我们使用<context:component-scan>扫描时也能扫描到。看注释@link意思即把@ControllerAdvice注解内部使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法应用到所有的 @RequestMapping注解的方法。

1.@ExceptionHandler(异常类)这个注解则表示Controller中任何一个方法发生异常,则会被注解了@ExceptionHandler的方法拦截到。对应的异常类执行对应的方法,如果都没有匹配到异常类,则采用近亲匹配的方式。

2.@ModelAttribute有三个作用

①绑定请求参数到命令对象:放在功能处理方法的入参上时,用于将多个请求参数绑定到一个命令对象,从而简化绑定流程,而且自动暴露为模型数据用于视图页面展示时使用;

②暴露表单引用对象为模型数据:放在处理器的一般方法(非功能处理方法)上时,是为表单准备要展示的表单引用对象,如注册时需要选择的所在城市等,而且在执行功能处理方法(@RequestMapping注解的方法)之前,自动添加到模型对象中,用于视图页面展示时使用;

③暴露@RequestMapping方法返回值为模型数据:放在功能处理方法的返回值上时,是暴露功能处理方法的返回值为模型数据,用于视图页面展示时使用。

@ControllerAdvice
public class CurrentUserControllerAdvice {

    private static final Logger log = LoggerFactory.getLogger(CurrentUserControllerAdvice.class);

    @ModelAttribute("currentUser")
    public CurrentUser getCurrentUser(Authentication auth, HttpServletRequest request, HttpServletResponse response) throws Exception {
        CurrentUser user = (auth == null) ? null : (CurrentUser) auth.getPrincipal();
        log.debug("CurrentUser={}, URL={}", user, request.getRequestURL());
        if (user != null) {
            log.debug("Username={}, Role={}", user.getUsername(), user.getRole());
        }
        return user;
    }

}

这段代码的意思则为把返回的user对象设置到Model中,对于之后的RequestMapping的方法调用可以直接取得到对应key值currentUser的value值。对于一个用户认证实现可以使用这个注解。

转载于:https://www.cnblogs.com/xiao--y/p/8966740.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值