CORS跨域请求:前后端分离
请求过滤器:
/*** OncePerRequestFilter保证在任何Servlet容器中都是一个请求只执行一次的过滤器。*/public class CorsFilter extends OncePerRequestFilter {@Overrideprotected void doFilterInternal(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws ServletException, IOException { Properties props = PropertiesLoaderUtils.loadAllProperties("cors.properties"); //允许的 客户端域名 resp.addHeader("Access-Control-Allow-Origin", props.getProperty("cors.allowed-origins")); //允许的 方法名 resp.addHeader("Access-Control-Allow-Methods", props.getProperty("cors.allowed-methods")); //允许服务端访问的客户端请求头,多个请求头用逗号分割,例如:Content-Type resp.addHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,token"); //预检验请求时间 resp.addHeader("Access-Control-Max-Age", props.getProperty("cors.max-age"));//30 min resp.addHeader("Access-Control-Allow-Credentials", "true"); chain.doFilter(req, resp);}}
web.xml中配置跨域过滤器:
<!--配置跨域请求的过滤器--><filter><filter-name>cors</filter-name><filter-class>com.jd.dashboard.cors.CrossFilter</filter-class></filter><filter-mapping><filter-name>cors</filter-name><url-pattern>/*</url-pattern></filter-mapping>
过滤器中的属性配置如下:
#跨域请求CORS全局配置属性值#允许访问的客户端域名,例如:http://web.xxx.comcors.allowed-origins=http://front.xx.com#允许访问的方法名cors.allowed-methods=POST, GET, OPTIONS, DELETE#允许服务端访问的客户端请求头,多个请求头用逗号分割,例如:Content-Typecors.allowed-headers=Content-Type#允许客户端访问的服务端响应头cors.exposed-headers=#是否允许请求带有验证信息,若要获取客户端域下的cookie时,需要将其设置为truecors.allow-credentials=truecors.max-age=1800
由于jsonp只支持GET方式的请求,所以这种方式比较推荐。
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。