前言
平时我们的SSM项目中我们可以使用web.xml配置拦截器,但是我们的springboot项目没有web.xml,所有我们的拦截器就需要自己来配置了。
需要先创建**.****.*****.config.LoginInterceptorConfigurer
配置类,实现**WebMvcConfigurer**
接口,并添加@Configuration
注解,重写其中的addInterceptors()
方法以注册拦截器:
@Configuration
public class LoginInterceptorConfigurer implements WebMvcConfigurer{
@Override
public void addInterceptors(InterceptorRegistry registry) {
HandlerInterceptor interceptor = new LoginInterceptor();
//因为我们下面会拦截所有的路径,这里可以将我们不需要拦截的路径保存到list集合中
List<String> excludeList = new ArrayList<>();
excludeList.add("/users/reg");
excludeList.add("/users/login");
excludeList.add("/districts/**");
excludeList.add("/products/**");
excludeList.add("/web/register.html");
excludeList.add("/web/login.html");
excludeList.add("/web/index.html");
excludeList.add("/web/product.html");
excludeList.add("/web/search.html");
excludeList.add("/bootstrap3/**");
excludeList.add("/images/**");
excludeList.add("/css/**");
excludeList.add("/js/**");
registry.addInterceptor(interceptor)
.addPathPatterns("/**")
.excludePathPatterns(excludeList);
}
}
注意上面的自定义类需要加上@Configuration
注解,不然不生效
我们需要自定义**.****.*****.interceptor.LoginInterceptor
拦截器类,实现**HandlerInterceptor**
接口,并重写preHandle()
方法,以决定拦截规则:
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 从参数request中获取session
HttpSession session = request.getSession();
// 判断session中有没有登录信息
if (session.getAttribute("uid") == null) {
// 没有登录信息,则重定向到登录页
response.sendRedirect("/web/login.html");
// 执行拦截,阻止运行
return false;
}
// 存在登录信息,直接放行
return true;
}
}
另外,需要我们在启动类上加上的我们@Configuration
注解,在@SpringBootApplication
上面下面都无所谓
好了,springboot的拦截器配置基本完成了