CORS过滤器在我的java应用程序中不起作用

时间:2018-04-26 09:22:48

标签: java tomcat web-applications cors servlet-filters

我正在使用jdk 8并在build.gradle中添加了tomcat-catalina,并在web.xml中配置了以下值,但在访问请求URL时它不会返回响应头。

的build.gradle:

compile group: 'org.apache.tomcat', name: 'tomcat-catalina', version: '8.5.29'

的web.xml

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
  <init-param>
    <param-name>cors.allowed.origins</param-name>
    <param-value>*</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.methods</param-name>
    <param-value>GET,POST,HEAD,OPTIONS,PUT</param-value>
  </init-param>
  <init-param>
    <param-name>cors.allowed.headers</param-name>
    <param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
  </init-param>
  <init-param>
    <param-name>cors.exposed.headers</param-name>
    <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
  </init-param>
  <init-param>
    <param-name>cors.support.credentials</param-name>
    <param-value>true</param-value>
  </init-param>
  <init-param>
    <param-name>cors.preflight.maxage</param-name>
    <param-value>10</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

它对我不起作用..

反应:

*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /myApplication/test?sample=value HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.47.0
> Accept: */*
> 
< HTTP/1.1 200 
< Content-Type: application/json;charset=utf-8
< Content-Length: 78
< Date: Thu, 26 Apr 2018 08:08:31 GMT
< 

我的自定义CorsFilter在我的应用程序中运行良好。

我错了什么?如何在我的应用程序中配置apache CorsFiler而不是自定义CorsFiler?

请提供您的意见。

1 个答案:

答案 0 :(得分:0)

我也发现了类似spring的框架问题。我通过在响应标头中添加 X-XSRF-TOKEN 解决了这个问题。

尝试添加。它可以解决问题。

res.addHeader("Access-Control-Allow-Headers", "x-requested-with, authorization, Content-Type, Authorization, credential, X-XSRF-TOKEN");