JAVA服务端配置允许跨域请求

原创
2016/11/13 01:05
阅读数 3.3K

CORS是一个W3C标准,全称是”跨域资源共享”(Cross-origin resource sharing)。 它允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。

1.加入CROS依赖的包

<dependency>
	<groupId>com.thetransactioncompany</groupId>
	<artifactId>java-property-utils</artifactId>
	<version>1.10</version>
</dependency>
<dependency>
	<groupId>com.thetransactioncompany</groupId>
	<artifactId>cors-filter</artifactId>
	<version>1.9.1</version>
</dependency>

2. web.xml 加入CORSFilter

<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.supportedMethods</param-name>
			<param-value>GET, POST, HEAD, PUT, DELETE</param-value>
		</init-param>
		<init-param>
			<param-name>cors.supportedHeaders</param-name>
			<param-value>Accept, Origin, X-Requested-With, Content-Type,
				Last-Modified</param-value>
		</init-param>
		<init-param>
			<param-name>cors.exposedHeaders</param-name>
			<param-value>Set-Cookie</param-value>
		</init-param>
		<init-param>
			<param-name>cors.supportsCredentials</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>CORS</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</fitler>

注意点

CORSFilter 放在最上边,最先被加载,不然无效
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
5 收藏
0
分享
返回顶部
顶部