目录
本篇博客将为大家介绍了如何在Spring Boot应用中实现基于JWT的登录拦截器,以保证未登录用户无法访问指定的页面。
一、配置拦截器进行登录校验
1. 在config层设置拦截器
我们首先在config层创建一个配置类,用来设置需要拦截的页面。在Spring Boot中,我们可以通过实现WebMvcConfigurer接口来配置拦截器。
创建LoginConfig类:
import com.bim.bimbookshop.interceptor.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 登录拦截配置类
*/
@Configuration // 表明这个是配置类
public class LoginConfig implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
/**
* 配置拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor) // 添加拦截器
.addPathPatterns("/**") // 配置拦截路径
.excludePathPatterns("/login/**", "/static/**", "/templates/**"); // 配置排除路径
}
}
这里的addPathPatterns("/**")表示拦截所有路径,而excludePathPatterns用于排除登录、注册等静态资源的路径。例如,/login/**表示排除所有与登录相关的请求。
2. 实现LoginInterceptor拦截器
接下来,我们需要在interceptor层创建一个拦截器类,用来判断用户是否已登录。


555

被折叠的 条评论
为什么被折叠?



