/** * * 註冊攔截器 * Created by SYSTEM on 2017/8/16. */ public class WebAppConfig extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { //註冊自定義攔截器,添加攔截路徑和排除攔截路徑 registry.addInterceptor(new InterceptorConfig()).addPathPatterns("api/path/**").excludePathPatterns("api/path/login"); } }
在web開發的過程當中,爲了實現登陸權限驗證,咱們每每須要添加一個攔截器在用戶的的請求到達controller層的時候實現登陸驗證,那麼SpringBoot如何添加攔截器呢?java
步驟以下:web
1.繼承WebMvcConfigureAdapter類,覆蓋其addInterceptors接口,註冊咱們自定義的攔截器:api
public class InterceptorConfig implements HandlerInterceptor{ private static final Logger log = LoggerFactory.getLogger(InterceptorConfig.class); /** * 進入controller層以前攔截請求 * @param httpServletRequest * @param httpServletResponse * @param o * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { log.info("---------------------開始進入請求地址攔截----------------------------"); HttpSession session = httpServletRequest.getSession(); if(!StringUtils.isEmpty(session.getAttribute("userName"))){ return true; } else{ PrintWriter printWriter = httpServletResponse.getWriter(); printWriter.write("{code:0,message:\"session is invalid,please login again!\"}"); return false; } } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { log.info("--------------處理請求完成後視圖渲染以前的處理操做---------------"); } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { log.info("---------------視圖渲染以後的操做-------------------------0"); } }
這樣咱們就能夠在用戶請求到達controller層實現登陸攔截了,全部用戶請求都會被攔截,在prehandle方法進行登陸判斷,返回true則驗證經過,不然失敗session