1.編寫攔截器類:
public class loginHandlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HttpSession session = request.getSession(); if(session.getAttribute("username")==null){ request.setAttribute("msg","請先登錄"); request.getRequestDispatcher("/").forward(request,response); return false; } else return true; } }
2.在mvc配置類中添加攔截器
//導入配置 @Configuration //繼承WebMvcConfigurer public class mvcConfig implements WebMvcConfigurer { //添加自定義攔截器 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new loginHandlerInterceptor()).addPathPatterns("/**") //配置不攔截的路徑 .excludePathPatterns("/","/login","/css/**","/js/**","/fonts/**","images/**"); } }
