java后台解决跨域问题
解决跨域问题的方式有很多,这里主要是添加注解的方式和采用添加拦截器的方法:
方法一、spring boot中只用在Controller类上添加一个“@CrossOrigin“注解就可以实现对当前controller 的跨域 访问了,当然这个标签也可以加到方法上。
@CrossOrigin public class CommonController { }
其他controller类继承以上这个类就可以解决跨域问题。
注意:“@CrossOrigin“注解要求jdk1.8以上版本
方法二、采用添加拦截器的方法
@Configuration public class WebConfig extends WebMvcConfigurerAdapter { @Autowired private EnvConfig envConfig; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new HandlerInterceptor() { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { boolean isTrue = envConfig.getIsDev();//判断是测试服才需要解决跨域问题 if (isTrue) { response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"); response.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,token"); } 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 { } }); }
}