java 服务端设置跨域

时间:2022-08-28 22:14:35
自:https://www.jianshu.com/p/0c67823550d6

setHeader(name, value) ; //如果Header中没有定义则添加,如果已定义则用新的value覆盖原用value值。
addHeader(name, value); // 如果Header中没有定义则添加,如果已定义则保持原有value不改变。


  • 简单点
// 最简单的处理方式
response.setHeader("Access-Control-Allow-Origin","*");
  • 完整点
// 这个可以用过滤器统一处理
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
            // CORS "pre-flight" request
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
            response.addHeader("Access-Control-Max-Age", "1800");//30 min
        }

2017-03-10 更新

  • 使用拦截器统一做跨域处理
@Component
public class CORSInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //添加跨域CORS
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested-With,content-type,token");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        return true;
    }
}
  • 最后启用拦截器就ok,以下展示在Spring-boot配置
public class WebConfigTest extends WebMvcConfigurerAdapter {
    @Autowired
    private CORSInterceptor corsInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(corsInterceptor);
    }
}
  • 效果


    java 服务端设置跨域