使用CORS实现JavaWeb跨域请求问题的方法
程序员文章站
2024-03-13 19:32:09
之前用jsonp 解决跨域问题,现在用cors实现跨域请求解决java 跨域问题:
主要代码如下
package com.hy.fliter;
import...
之前用jsonp 解决跨域问题,现在用cors实现跨域请求解决java 跨域问题:
主要代码如下
package com.hy.fliter; import java.io.ioexception; import javax.servlet.filter; import javax.servlet.filterchain; import javax.servlet.filterconfig; import javax.servlet.servletexception; import javax.servlet.servletrequest; import javax.servlet.servletresponse; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import org.apache.commons.httpclient.httpstatus; /** * created by wangshuai on 2016/7/30. */ public class corsfilter implements filter { @override public void init(filterconfig filterconfig) throws servletexception { } @override public void dofilter(servletrequest servletrequest, servletresponse servletresponse, filterchain filterchain) throws ioexception, servletexception { httpservletresponse response = (httpservletresponse) servletresponse; httpservletrequest request = (httpservletrequest) servletrequest; // 指定允许其他域名访问 response.setheader("access-control-allow-origin", "*"); // 响应类型 response.setheader("access-control-allow-methods", "post, get, delete, options, delete"); // 响应头设置 response.setheader("access-control-allow-headers", "content-type, x-requested-with, x-custom-header, haiyi-access-token"); if ("options".equals(request.getmethod())){ response.setstatus(httpstatus.sc_no_content); } filterchain.dofilter(servletrequest, servletresponse); } @override public void destroy() { } }
web.xml 代码如下配置
<filter> <filter-name>cors</filter-name> <filter-class>com.hy.fliter.corsfilter</filter-class> </filter> <filter-mapping> <filter-name>cors</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
以上所述是小编给大家介绍的使用cors实现javaweb跨域请求问题的方法,希望对大家有所帮助