How to configure Tomcat for cross-origin access?
To configure cross-origin access in Tomcat, you can either modify the Tomcat configuration file or set it in the code.
- Configure the web.xml file in Tomcat:
Locate the web.xml file in the conf directory of Tomcat, open it, and find the following code block:
<!-- ==================== Default MIME Type Mappings ==================== -->
Add the following code below this code block:
<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>
This configuration allows all domains to make cross-origin requests and also allows for modifications to the allowed methods and headers as needed.
- Set up in the code:
Add the following code in the corresponding Servlet or Filter:
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,HEAD,OPTIONS,PUT");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers");
Similarly, this configuration allows all domains to access resources across domains, and the allowed methods and headers can be modified according to specific needs.
After the configuration is completed, restart Tomcat to apply the settings.