原因:
实际上发送了两次请求,第一次为options请求,第二次才get/post…请求
在options请求中,不会携带请求头的参数,所以在拦截器上获取请求头为空,自定义的拦截器拦截成功
第一次请求不能通过,就不能获取第二次的请求了get/post…
第一次请求不带参数,第二次请求才带参数
解决方案: 添加 if 这段代码快即可
后面的代码我是用来判断用户是否登入和判断token令牌是否过期
拦截器
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
System.out.println("OPTIONS请求,放行");
return true;
}
String token = request.getHeader("token");
if(ObjectUtils.isEmpty(token)) { //这里是判断用户是否登入
throw new NullTokenException("你还未登入,请登入");
}
String name = TokenManger.parseUserNameFromToken(token); //这个是用于判断令牌过期
return true;
}
注册拦截器并放行一些资源。 其实下面所有的代码无关标题
package com.chao.config;
import com.chao.intercepter.LoginInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpHeaders;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
//@Profile("prod") 该注解是说:该配置只在prod环境下生效
public class WebMvcConfig implements WebMvcConfigurer {
@Autowired
LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor)
.excludePathPatterns("/sys/login")
.excludePathPatterns("/doc.html", "/oss/upload","/excel/uploadEmployee",
"/swagger-resources/**", "/webjars/**", "/v2/**");
}
}
自定义异常
public class NullTokenException extends Exception{
public NullTokenException() {
super();
}
public NullTokenException(String message) {
super(message);
}
}
捕获全局异常
package com.chao.advice;
import com.chao.exception.NullTokenException;
import com.chao.uilts.CR;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
@ResponseBody
//处理全局异常
public class ExceptionAdvice {
@ExceptionHandler(ExpiredJwtException.class)
public CR handleExpiredJwtException(ExpiredJwtException e){
return CR.error("501","用户信息已过期,请重新登入");
}
@ExceptionHandler(NullTokenException.class)
public CR handleNullTokenException(NullTokenException e){
return CR.error("502",e.getMessage());
}
@ExceptionHandler(Exception.class)
public CR handleException(Exception e){
return CR.error("500","服务器出错.....");
}
}



