优雅的实现拦截器及统一异常处理

2018-04-17 17:43:45 浏览数 (1)

面向所有Controller的方法做拦截,获取Cookie信息
代码语言:javascript复制
@Aspect@Componentpublic class HomeworkAuthorizeAspect {    private Logger log = LoggerFactory.getLogger(HomeworkAuthorizeAspect.class);    @Pointcut("execution(public * com.xxx.homework.controller.*.*(..))")    public void verify(){}    @Before("verify()")    public void doVerify(){        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();        HttpServletRequest request = attributes.getRequest();        // Cookie 查询        Cookie cookie = CookieUtil.get(request, CookieConstant.TOKEN);        if(null == cookie){            log.warn("Cookie中查不到token");            throw new AuthorizeException();        }    }}
拦截自定义异常

自定义异常,向上抛出异常进行统一拦截

代码语言:javascript复制
@ControllerAdvicepublic class AuthorizeExceptionHandler {    @ExceptionHandler(value = AuthorizeException.class)    public ModelAndView handlerAuthorizeException(){        return new ModelAndView("");    }}

0 人点赞