public interface MappingInterceptor extends HandlerInterceptor {
String[] addPathPatterns();
String[] excludePathPatterns();
int order();
}
@Component
public class CrossOriginInterceptor implements MappingInterceptor {
private static final Logger logger= LoggerFactory.getLogger(CrossOriginInterceptor.class);
@Override
public String[] addPathPatterns() {
return new String[]{"/**"};
}
@Override
public String[] excludePathPatterns() {
return new String[0];
}
@Override
public int order() {
return 0;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.info("允许的头信息"+request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
//是否允许浏览器携带用户身份信息(cookie)
response.setHeader("Access-Control-Allow-Credentials","true");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
Exception ex) throws Exception {
}
}
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Autowired
private CrossOriginInterceptor crossOriginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(crossOriginInterceptor).addPathPatterns(crossOriginInterceptor.addPathPatterns());
}
}
原文:https://www.cnblogs.com/eternityz/p/12243224.html