Java添加全局请求拦截器
1. 创建一个拦截器LoginInterceptor
@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("拦截URL,查看是否已登录");
HttpSession session = request.getSession();
if (session.getAttribute(USER_LOGIN_STATE) == null || session != null) {
throw new BusinessException(ErrorCode.NOT_LOGIN, "访问前请登录");
}
return true;
}
}
2. 在WebMvcConfiguration中添加拦截器
@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
@Autowired
private LoginInterceptor loginInterceptor;
/**
* 添加全局请求拦截器
* @param registry
*/
public void addInterceptors(InterceptorRegistry registry) {
log.info("开始添加全局请求拦截器");
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/**")
.excludePathPatterns("/user/login")
.excludePathPatterns("/user/register");
}
}
我在写这个全局请求拦截器的时候的时候遇到了一个问题:
我在配置文件中配置了
server.servlet.context-path: /api
而在排除路径时如果写成excludePathPatterns(“/api/user/login”)会导致排除不了这个路径,必须要将/api去掉,即"/user/login"才能排除这个路径。
总之拦截路径的书写似乎忽略了这个配置。