在Spring Secondary Servlet中启用CORS

时间:2016-07-25 04:06:38

标签: spring cors

我正在使用Spring boot的ServletRegistrationBean注册辅助servlet

@Configuration
public class CxfServletRegister {   
@Bean
public ServletRegistrationBean getODataServletRegistrationBean() {
    ServletRegistrationBean odataServletRegistrationBean = new ServletRegistrationBean(new CXFNonSpringJaxrsServlet(), "/odata.svc/*");
    Map<String, String> initParameters = new HashMap<String, String>();
    initParameters.put("javax.ws.rs.Application", "org.apache.olingo.odata2.core.rest.app.ODataApplication");
    initParameters.put("org.apache.olingo.odata2.service.factory", "com.cce.utils.JPAServiceFactory");
    odataServletRegistrationBean.setInitParameters(initParameters);
    return odataServletRegistrationBean;
}
}

我正在使用Apache Olingo构建OData应用程序。我希望为我的服务启用CORS。 如何为此servlet启用CORS?

PS我已经尝试过Spring:入门指南中的WebConfigurer bean

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/greeting-javaconfig").allowedOrigins("*");
        }
    };
}

这不起作用,可能是因为这是配置spring web的默认调度程序servlet而不是使用ServletRegistrationBean配置的附加servlet

1 个答案:

答案 0 :(得分:1)

我发现了一种可行的方法: https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

@Configuration
public class MyConfiguration {

@Bean
public FilterRegistrationBean corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("http://domain1.com");
    config.addAllowedHeader("*");
    config.addAllowedMethod("*");
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
    bean.setOrder(0);
    return bean;
}

}