Springboot使用AuthInterceptorAdapter——過濾攔截器


一、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")方法是排除登錄訪問路徑;


免責聲明!

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



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