spring - 在 Spring Secondary Servlet 中启用 CORS

标签 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

最佳答案

我在这里找到了一种可行的方法: 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;
       }
    }

关于spring - 在 Spring Secondary Servlet 中启用 CORS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38559554/

相关文章:

java - Spring MVC中如何返回JSP选择框的值?

java - Spring 和线程安全

java - jpa查询错误:the multi-part identifier could not be bound

reactjs - 将图像上传到 AWS S3 存储桶 ReactJS 时 POST 403 禁止 CORS 响应

java - 请求中不存在 'Access-Control-Allow-Origin' header

java - 用于 OneToMany 的 Spring RowMapper?

java - 如何从参数请求的值迭代

node.js - Socket.io + Node Js + Angular 2 - CORS header 'Access-Control-Allow-Origin' 丢失

asp.net-core - Blazor oauth2 被 CORS 阻止

angularjs - 带有 Windows 身份验证的 WebAPI CORS - 允许匿名 OPTIONS 请求