tomcat配置CORS,支持JS跨域访问

1. Place the CORS JAR and its dependency in the CLASSPATH

Download the cors-filter-<version>.jar file and itsjava-property-utils-<version>.jar dependency, and put them into the CLASSPATHof your web server.

cors-filter-1.8.jar java-property-utils-1.9.jar

If you have Apache Tomcat there are two CLASSPATHchoices: If you intend to use CORS with a single web applicationput the JAR file in

$CATALINA_HOME/webapps/<your-web-app>/WEB-INF/lib/

To make CORS available globally, to all web applications, place the JAR in

$CATALINA_HOME/lib/

2. Add CORS configuration to web.xml

Open the WEB-INF/web.xml file of the web application where youintend to enable CORS and add a CORS Filter declaration and mapping.

The XML declaration to load the CORS filter:

<filter>
	<filter-name>CORS</filter-name>
	<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>

Then declare a filter mapping to tell the web server whichservlets or URLs should be cross-domain-request enabled.

Example of applying the CORS filter to a single servlet:

<filter-mapping>
        <filter-name>CORS</filter-name>
        <servlet-name>MyServlet</servlet-name>
</filter-mapping>

And how to apply the CORS filter to all web app URLs:

<filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

Have a look at the web.xmlof the demo CORS application included with the download package to seea complete CORS filter declaration and mapping example.

Finally, remember to restart your web server for the installation to take effect.

Important note:By default the CORS Filter will apply a "public access" CORS policy, allowingall cross-site requests through (including credentials/cookies). Leavingthe CORS Filter at this setting would actually be fine for most situationsas CORS is not about adding server security; its primary intent is to protect thebrowser - the legitimate JavaScript apps running in it and the user's confidential data, such as cookies.

扫描二维码关注公众号,回复: 4573239 查看本文章

If you want to modify the default CORS Filter behaviour, proceed tothe configuration instructions.

猜你喜欢

转载自blog.csdn.net/jiayu8706/article/details/34118155