跨域请求,设置服务端请求的Origin,Access-Control-Allow-Origin,使用filter过滤器,对每次请求的这两项数据进行设置。
对应代码 ,设置一个filter(当前类继承自 implementsFilter)
publicvoiddoFilter(ServletRequestreq, ServletResponseres, FilterChainchain)throwsIOException, ServletException {
HttpServletResponseresponse= (HttpServletResponse)res;
HttpServletRequestrequest= (HttpServletRequest)req;
Stringorigin=request.getHeader("Origin");
response.setHeader("Access-Control-Allow-Origin",origin);
response.setHeader("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age","3600");
response.setHeader("Access-Control-Allow-Headers","Content-Type,jsonRequest");//这里“Access-Token”是我要传到后台的内容key
response.setHeader("Access-Control-Allow-Credentials","true");
Stringmethod=request.getMethod();
if(method.equalsIgnoreCase("OPTIONS")){
res.getOutputStream().write("Success".getBytes("utf-8"));
}else{
chain.doFilter(req,res);
}
}
b、在项目的web问价下添加如下代码
主要作用是注册过滤器拦截请求
<filter>
<filter-name>corsFilter</filter-name>
<filter-class>com.eifini.common.filter.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>