基于springboot配置拦截器
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/**"); } }