首页 > 编程语言 > 详细

Springboot使用AuthInterceptorAdapter——过滤拦截器

时间:2020-05-27 17:54:52      阅读:190      评论:0      收藏:0      [点我收藏+]

一、HandlerInterceptorAdapter类

  Springboot 的拦截器概念上和Filter 很像,拦截发送到 Controller 的请求和给出的响应;HandlerInterceptorAdapter类提供了请求处理的3个方法;

//拦截于请求刚进入时,进行判断,需要boolean返回值,如果返回true将继续执行,如果返回false,将不进行执行。一般用于登录校验    
public
boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {   return true; }
//拦截于方法成功返回后,视图渲染前,可以对modelAndView进行操作
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception { }
//拦截于方法成功返回后,视图渲染前,可以进行成功返回的日志记录
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception { }
//
不是HandlerInterceptor的接口实现,是AsyncHandlerInterceptor的,AsyncHandlerInterceptor实现了HandlerInterceptor
public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { }

二、鉴权AuthInterceptor

  继承HandlerInterceptorAdapter类,重写了preHandle方法,对请求登录人角色进行权限鉴定;

@Slf4j
public class AuthInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        request.setCharacterEncoding("UTF-8");if (true) {
            return super.preHandle(request, response, handler);
        }
        throw new AuthException(EnumResult.PERMISSION_ERROR);
    }
}

三、注册拦截器

  注册拦截器很简单,只需要配置一个类,使其实现 WebMvcConfigurer 接口即可;其中还可以设定多个不同的拦截器,并且映射到不同的 url 地址上。

@EnableWebMvc
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
  @Override 
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(
new AuthInterceptor())//添加拦截器
         .addPathPatterns("/**") .excludePathPatterns("/login");
  }
}

  注:addPathPatterns("/**")对所有请求都拦截;excludePathPatterns("/login")方法是排除登录访问路径;

Springboot使用AuthInterceptorAdapter——过滤拦截器

原文:https://www.cnblogs.com/happy2333/p/12974444.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!