简体   繁体   中英

CORS Request Error Tomcat 7 & Java Servlet

I somehow can't get this to work. I have a Java Servlet running on a Tomcat 7 Server (running on localhost:8080) and I want to make a PUT-Request from a different Webservice (running on localhost:80). I have added the CORS-Accept-Header in the Servlet-Code as well as in the Tomcat Configuration, but somehow I always get this error when I try to make the PUT-Request:

[Error] Failed to load resource: Origin http://localhost is not allowed by Access-Control-Allow-Origin.

In my Java Servlet I have the following headers defined:

response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "86400");

Before using response.addHeader I used response.setHeader, but this made no difference in my case. In the tomcat web.xml config file I have added the following lines:

 <filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
    <init-param>
        <param-name>cors.allowed.methods</param-name>
        <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowed.origins</param-name>
        <param-value>*</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

As described in the tomcat-7-docs: https://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter

I really can't see what I'm missing

OK, I got it. The problem was a pretty simple one, but it was causing me so much trouble. I'm programming with eclipse and I'm new to this IDE. Eclipse seems to use it's own copy of Tomcat in a binary .metadata-folder in my workspace. If anyone else has this issue: Either change the web.xml-File in the .metadata-folder of eclipse (it holds a 1:1 copy of tomcat in there), or set eclipse not to use it's own copy of tomcat.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM