Keywords: Tomcat | CORS | Access-Control-Allow-Origin
Abstract: This article delves into the core methods for configuring Cross-Origin Resource Sharing (CORS) in Tomcat containers, focusing on how to implement the Access-Control-Allow-Origin: * header using third-party CORS filters. Based on high-scoring Stack Overflow answers, it details configuration steps, common issues, and solutions, covering key technical aspects such as dependency management and web.xml parameter optimization. By comparing multiple answers, it provides a complete practical guide from basic setup to advanced customization, helping developers resolve CORS configuration challenges in Tomcat 6.0.6 and later versions.
In web development, Cross-Origin Resource Sharing (CORS) is a critical mechanism for enabling data interaction between different origins. Tomcat, as a widely used Java web server, often presents CORS configuration challenges due to version differences and dependency management issues. This article uses Tomcat 6.0.6 as an example to systematically explain how to effectively set the Access-Control-Allow-Origin: * header via third-party filters.
Core Configuration Method
Based on best practices, using com.thetransactioncompany.cors.CORSFilter is recommended for CORS implementation. The configuration involves two key steps: dependency inclusion and web.xml setup.
Dependency Management
First, ensure the CORS filter JAR file is correctly integrated. A common mistake is placing cors.jar only in Tomcat's /lib directory while neglecting project-level dependencies. The correct approach is to add the dependency to the project build path via Maven or manually. For example, in a Maven project, add to pom.xml:
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>1.3.2</version>
</dependency>
This ensures the filter class is available at runtime, avoiding common issues like ClassNotFoundException.
Detailed web.xml Configuration
In web.xml, define the filter and its mapping. The following configuration is based on optimized parameters:
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowOrigin</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.supportsCredentials</param-name>
<param-value>false</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>accept, authorization, origin</param-value>
</init-param>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, POST, HEAD, OPTIONS</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Key parameter explanations:
cors.allowOrigin: Set to*to allow all origins, but note compatibility withcors.supportsCredentials.cors.supportsCredentials: Must befalsewhenallowOriginis*, otherwise browsers will reject requests.cors.supportedHeaders: Includes core headers likeaccept,authorization, andoriginto ensure cross-origin requests carry necessary information.cors.supportedMethods: Defines allowed HTTP methods, withOPTIONSbeing crucial for preflight requests.
Common Issues and Optimizations
During configuration, developers often encounter issues where headers do not take effect. Supplemental answers indicate that cors.supportedHeaders may need expansion to Accept, Origin, X-Requested-With, Content-Type, Last-Modified to cover more scenarios. Additionally, Tomcat 7.0.41 and later versions include a built-in CORS filter configurable via official documentation, but this article focuses on third-party solutions for older version compatibility.
Custom Filter Alternative
For simple needs, a custom filter can be written. Example code:
import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CORSFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.addHeader("Access-Control-Allow-Origin", "*");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {}
@Override
public void destroy() {}
}
After configuration in web.xml, this filter adds Access-Control-Allow-Origin: * to all responses. However, this approach has limited functionality and lacks fine-grained control.
Conclusion
By properly configuring third-party CORS filters, cross-origin support can be effectively implemented in Tomcat. Key points include ensuring correct dependency inclusion, optimizing web.xml parameters, and handling conflicts between allowOrigin and supportsCredentials. For Tomcat 7.0.41+ users, exploring the built-in filter can simplify setup. In practice, using browser developer tools to verify headers are added as expected is recommended for quick troubleshooting.