主要分成两步走即可
1、实现拦截器接口
2、配置类添加自定义的拦截器
第一步:实现拦截器接口,代码如下
@Component // 注解必要有,声明组件 放入到容器当中 public class AuthIntercept implements HandlerInterceptor { // 实现 spring的拦截器接口 HandlerInterceptor // 模仿登录 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws ServletException, IOException { if (request.getSession().getAttribute("loginfo")!=null){// 已经登陆成功 return true; //则允许继续执行 }else { System.out.println("跳转到登陆页面"); // request.getRequestDispatcher("/user/login").forward(request,response); response.sendRedirect("/user/login");// 拦截后跳转到其他页面 return false;// 不继续执行 } } }
第二步:配置类中增加自定义的拦截器
@Configuration public class WebConfig implements WebMvcConfigurer { @Autowired AuthIntercept authIntercept;
@Override public void addInterceptors(InterceptorRegistry registry) { // addPathPatterns("/**") 表示拦截所有的请求, // excludePathPatterns("/login", "/register") 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问 InterceptorRegistration loginRegistry = registry.addInterceptor(authIntercept) .addPathPatterns("/**") .excludePathPatterns("/user/login", "/user/register"); // 几种写法均可 // 拦截路径 // 排除路径 loginRegistry.excludePathPatterns("/"); loginRegistry.excludePathPatterns("/error"); loginRegistry.excludePathPatterns("/login"); loginRegistry.excludePathPatterns("/loginout"); loginRegistry.excludePathPatterns("/WEB-INF/jsp/**/*.jsp"); // 排除资源请求 loginRegistry.excludePathPatterns("/static/**/*.css"); loginRegistry.excludePathPatterns("/static/**/*.js"); loginRegistry.excludePathPatterns("/static/**/*.*"); loginRegistry.excludePathPatterns("/static/**/*.png"); }
}