SpringBoot配置攔截器
阿新 • • 發佈:2022-03-11
實現 HandlerInterceptor 介面
@Slf4j public class LoginInterceptor implements HandlerInterceptor { /** * 目標方法執行之前 * @param request * @param response * @param handler * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String requestURI = request.getRequestURI(); // log.info("攔截的請求路徑",requestURI); HttpSession session = request.getSession(); Object loginUser = session.getAttribute("loginUser"); if(loginUser != null){ return true; } request.setAttribute("msg","請先登入"); request.getRequestDispatcher("/").forward(request,response); return false; } /** * 目標方法執行之後 * @param request * @param response * @param handler * @param modelAndView * @throws Exception */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } /** * 頁面渲染以後 * @param request * @param response * @param handler * @param ex * @throws Exception */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
把該攔截器新增到 WebMvcConfigurer
@Configuration public class AdminWebConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoginInterceptor()) .addPathPatterns("/**")//所有請求都被攔截,包括靜態資源 .excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**");//放行的請求 } }