Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

Set CORS header in Tomcat

I had a static website hosted by Tomcat.

How to set a header for my site like:Access-Control-Allow-Origin: *

They are all static file, not any servlet application.

question from:https://stackoverflow.com/questions/16296145/set-cors-header-in-tomcat

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If it's a static site, then starting with Tomcat 7.0.41, you can easily control CORS behavior via a built-in filter.

References:

Pretty much the only thing you have to do is edit the global web.xml in CATALINA_HOME/conf and add the filter definition:

     <!-- ================== Built In Filter Definitions ===================== -->

      ...

     <filter>
       <filter-name>CorsFilter</filter-name>
       <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
     </filter>
     <filter-mapping>
       <filter-name>CorsFilter</filter-name>
       <url-pattern>/*</url-pattern>
     </filter-mapping>

    <!-- ==================== Built In Filter Mappings ====================== -->

Be aware, though, that Firefox does not like Access-Control-Allow-Origin: * and requests with credentials (cookies): when responding to a credentialed request, server must specify a domain, and cannot use wild carding.

If you want to debugs requests in this situation, please be aware that CORS headers are only sent if there is a cross-origin request according to this flow-chart. CORS flow chart

(tomcat.apache.org/tomcat-8.0-doc/images/cors-flowchart.png)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...