鏈接:https://blog.csdn.net/zyp1376308302/article/details/81257510
(侵刪)
實現攔截器的兩個步驟
- 自定義攔截器實現HandlerInterceptor接口
- 創建一個配置類繼承WebMvcConfigurerAdapter類並重寫addInterceptors方法
代碼
1、自定義攔截器
@Component public class AdminLoginInterceptor implements HandlerInterceptor { // 在請求處理之前調用,只有返回true才會執行請求 @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { // 得到session HttpSession session = httpServletRequest.getSession(true); // 得到對象 Object admin = session.getAttribute("admin"); // 判斷對象是否存在 if(admin!=null){ return true; }else{ // 不存在則跳轉到登錄頁 httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login/adminLogin"); return false; } } // 試圖渲染之后執行 @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
} // 在請求處理之后,視圖渲染之前執行 @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }
2、自定義配置類繼承WebMvcConfigurerAdapter
@SpringBootConfiguration public class AdminLoginAdapter extends WebMvcConfigurerAdapter { @Autowired AdminLoginInterceptor adminLoginInterceptor;
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/admin/**").excludePathPatterns("/login/**"); super.addInterceptors(registry); } }
.addPathPatterns("/admin/**") :添加需要過濾的路徑
.excludePathPatterns("/login/**") :去掉不需要過濾的路徑