SpringBoot如何配置拦截器呢?
下文笔者讲述SpringBoot配置拦截器的方法分享,如下所示
一、编写拦截器实现类,实现HandlerInterceptor接口
public class MyInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 统一拦截,判断是否有登录(输入有账号密码,userName就会存储到session) Object value = request.getSession().getAttribute("Lotus"); if (value != null) { return true; }else { request.getRequestDispatcher("/WEB-INF/views/user/login.jsp").forward(request, response); return false; } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
二、编写拦截器配置类,实现WebMvcConfigurer接口
@Configuration //一定要加上这个注解,成为Springboot的配置类,不然不会生效 public class WebMvcConfiguration implements WebMvcConfigurer { @Override //拦截器配置 public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()) //拦截器注册对象 .addPathPatterns("/**") //指定要拦截的请求 .excludePathPatterns("/user/login"); //排除请求 } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。