Set CORS header in Tomcat
我有一个由Tomcat托管的静态网站。
如何为我的网站设置标题,如:
它们都是静态文件,而不是任何servlet应用程序。
如果它是静态站点,那么从Tomcat 7.0.41开始,您可以通过内置过滤器轻松控制CORS行为。
您要做的唯一事情就是编辑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | amp;lt;!-- ================== Built In Filter Definitions =====================amp;gt; ... amp;lt;filamp;gt; amp;lt;filter-namp;gt;CorsFilamp;lt;/filter-namp;gt; amp;lt;filter-clamp;gt;org.apache.catalina.filters.CorsFilamp;lt;/filter-clamp;gt; amp;lt;/filamp;gt; amp;lt;filter-mappamp;gt; amp;lt;filter-namp;gt;CorsFilamp;lt;/filter-namp;gt; amp;lt;url-pattamp;gtamp;lt;/url-pattamp;gt; amp;lt;/filter-mappamp;gt; amp;lt;!-- ==================== Built In Filter Mappings ======================amp;gt; |
但请注意,Firefox不喜欢
这是一个非常基本的过滤器,它将添加CORS头。 请注意,默认情况下,这将启用所有域和方法,因此您应该自定义它以满足您的需要。
它还需要是web.xml中的第一个过滤器。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 | package com.conductiv.api.listener; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CORSFilter implements Filter { public void destroy() { } public static String VALID_METHODS ="DELETE, HEAD, GET, OPTIONS, POST, PUT"; public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException { HttpServletRequest httpReq = (HttpServletRequest) req; HttpServletResponse httpResp = (HttpServletResponse) resp; // No Origin header present means this is not a cross-domain request String origin = httpReq.getHeader("Origin"); if (origin == null) { // Return standard response if OPTIONS request w/o Origin header if ("OPTIONS".equalsIgnoreCase(httpReq.getMethod())) { httpResp.setHeader("Allow", VALID_METHODS); httpResp.setStatus(200); return; } } else { // This is a cross-domain request, add headers allowing access httpResp.setHeader("Access-Control-Allow-Origin", origin); httpResp.setHeader("Access-Control-Allow-Methods", VALID_METHODS); String headers = httpReq.getHeader("Access-Control-Request-Headers"); if (headers != null) httpResp.setHeader("Access-Control-Allow-Headers", headers); // Allow caching cross-domain permission httpResp.setHeader("Access-Control-Max-Age","3600"); } // Pass request down the chain, except for OPTIONS if (!"OPTIONS".equalsIgnoreCase(httpReq.getMethod())) { chain.doFilter(req, resp); } } public void init(FilterConfig config) throws ServletException { } } |
您需要添加
1 | <code<filamp;gt;amp;lt;filter-namp;gt;heaamp;lt;/filter-namp;gt;amp;lt;filter-clamp;gt;amp;lt;/filter-clamp;gtamp;lt;/filamp;gtamp;lt;filter-mappamp;gt;amp;lt;filter-namp;gt;heaamp;lt;/filter-namp;gt;amp;lt;url-pattamp;gtamp;lt;/url-pattamp;gtamp;lt;/filter-mappamp;gt; |