spring设置跨域

2018/06/17 javaweb

设置跨域访问的两种解决办法

1. 通过在controller类上或方法上添加@CrossOrigin注解实现跨域访问(推荐使用)

2. 添加自定义拦截器

public class CORSInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader("Access-Control-Allow-Origin","*");
        response.setHeader("Access-Control-Allow-Credentials","true");
        response.setHeader("Access-Control-Allow-Methods","GET,PUT,POST,DELETE,HEAD,OPTIONS");
        response.setHeader("Access-Control-Max-Age","3600");
        response.setHeader("Access-Control-Allow-Headers","x-requested-with,content-type");
        return super.preHandle(request, response, handler);
    }
}
@Component
public class InterceptorConfiguration extends WebMvcConfigurationSupport {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CORSInterceptor());
        super.addInterceptors(registry);
    }
}

Search

    Post Directory