1. 程式人生 > >springboot(5)——攔截器

springboot(5)——攔截器

  • 1、使用註解@Configuration配置攔截器
  • 2、繼承WebMvcConfigurerAdapter
  • 3、重寫addInterceptors 註冊新增需要的攔截器,匹配地址

編寫一個監聽器

// CommonInterceptor.java 獲取專案基本路徑並設定到httpServletRequest屬性值中

public class CommonInterceptor implements HandlerInterceptor {

    /**
     * 請求處理之前呼叫(Controller方法呼叫之前)
     */
    @Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { String path = httpServletRequest.getContextPath(); String scheme = httpServletRequest.getScheme(); String serverName = httpServletRequest.getServerName(); int
port = httpServletRequest.getServerPort(); String basePath = scheme + "://" + serverName + ":" + port + path; httpServletRequest.setAttribute("basePath", basePath); return true; } /** * 請求處理之後呼叫, 但是在檢視被渲染之前(Controller方法呼叫之後) */ @Override public void postHandle
(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } /** * 在整個請求結束之後被呼叫, 也就是在DispatcherServlet 渲染了對應的檢視之後執行 * (主要用於進行資源清理工作) */ @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }

註冊監聽器

@Configuration
public class CommonInterceptorConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 註冊攔截器, 按順序執行
        registry.addInterceptor(new CommonInterceptor()).addPathPatterns("/**").excludePathPatterns("/user/login");; // addPathPatterns("/api/**");

        //   /a/** 和 /b/**的請求 要經過AInterceptor 攔截
//        registry.addInterceptor(new AInterceptor()).addPathPatterns("/a/**").addPathPatterns("/b/**");
    }
}
  • 1、攔截器按順序執行
  • 2、addPathPatterns 新增路徑匹配
  • 3、preHandlepostHandleafterCompletion 攔截器回撥中 return true; 為放行。前面監聽到的攔截器不放行(return false;)的話,後面的攔截器監聽不到(不執行)