场景:目前有项目A(基于servlet的WEB项目),和项目B(基于spring boot的WEB项目),使用同一CAS提供单点登陆,如今须要两个项目互相调用接口数据,因此涉及到ajax的跨域请求java
调研:通过调研发现目前的ajax跨域解决方案有两种,jsonp和cors,其中jsonp须要在返回值中携带回调函数,cors则须要在响应头中附加指定参数。比对实现方式和优劣点,决定使用cors来实现web
CORS原理:服务器在收到请求以后,在响应参数中加入,Access-Control-Allow-Origin,Access-Control-Allow-Methods,Access-Control-Max-Age,Access-Control-Allow-Headers,Access-Control-Allow-Credentials等参数,浏览器在接收到返回值后会经过这些参数的设置来判断服务器是否支持跨域请求。因此,使用cors的方法就是经过设置过滤器,在指定请求的响应头中添加参数便可,传统的WEB项目,须要在web.xml中设置,而spring boot项目能够经过注解来设置ajax
1,servlet的WEB项目实现CORSspring
服务器端新建过滤器类json
package com.tas.util;
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.HttpServletResponse;
/**
* 跨域支持
*/
public class SimpleCORSFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader("Access-Control-Allow-Origin", "http://localhost");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with");
// 是否支持cookie跨域
httpServletResponse.addHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
在web.xml中配置过滤器,注意过滤器要配置在sevrlet和cas的过滤器以前跨域
Simple CORSFilter
com.tas.util.SimpleCORSFilter
Simple CORSFilter
/*
这样的配置就完成了,须要注意的是,在须要跨域访问该项目的网页中,若是须要传递cookie,则要在ajax中打开withCredentials,以下浏览器
$.ajax({
url:"http://localhost:8080/tasociety/IndexController.crossdomainTest.do",
type: "get",
dataType:"json",
xhrFields: {
withCredentials: true
},
crossDomain: true,
success:function (data) {
alert("12345");
console.log(data);
}
})
2,spring boot 的WEB项目实现CORS服务器
由于有默认的注解@CrossOrigin,因此直接配置在controller上就行了cookie
package com.castmember.Controller;
@CrossOrigin(origins = "http://localhost:8080",allowCredentials = "true")
@Controller
public class IndexController {
@Autowired
SysUserDao sysuserdao;
@RequestMapping("/")
public String index(Model model) {
Optional useropt= sysuserdao.findById((long)1);
model.addAttribute("user", useropt.orElse(null));
return "index";
}
}
在须要跨域访问该项目的网页中,若是须要传递cookie,则要在ajax中打开withCredentials,以下app
$.ajax({
url:"http://localhost/castmember/crossdomaindata",
type: "get",
dataType:"json",
xhrFields: {
withCredentials: true
},
crossDomain: true,
success:function (data) {
alert("12345");
console.log(data);
}
})
如果觉得《ajax跨域请求(cors实现) ajax跨域请求(CORS实现)》对你有帮助,请点赞、收藏,并留下你的观点哦!