一、创建interceptor包,在interceptor中创建一个拦截器并实现HandlerInterceptor
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//拦截逻辑
Object user = request.getSession().getAttribute("loginUser");
if (user == null) {
System.out.println("没有权限请先登陆");
//未登陆,返回登陆界面
request.setAttribute("msg","没有权限请先登陆");
request.getRequestDispatcher("/login").forward(request,response);
return false;
} else {
//已登陆,放行请求
return true;
}
}
}
二、创建一个SpringMvc配置类并实现WebMvcConfigurer类
@Configuration
public class MyWebMvcConfiguration implements WebMvcConfigurer {
@Autowired
LoginHandlerInterceptor loginHandlerInterceptor;
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/login");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
}
//注册拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
//拦截所有的请求
registry.addInterceptor(loginHandlerInterceptor).addPathPatterns("/**").excludePathPatterns("/login", "/register").excludePathPatterns("/static/**");
}
}
注意:在SpringBoot中,只能通过创建SpringMVC配置文件来注册拦截器,
.addPathPatterns("/**")表示拦截所有的请求,
excludePathPatterns表示路径不需要拦截哪些路径
一定要在这里排除拦截static路径下的静态文件,或者在SpringBoot配置文件上配置,否则页面加载不到样式