原
ssm框架解决跨域问题
一:自定义一个Filter。package com.fyq.filter;
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 com.fyq.utils.ConstantUtils;
// 设置跨域[http升级为https后引起跨域问题]
public class CorsFilter implements Filter {
private boolean isCross = false;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
String isCrossStr = filterConfig.getInitParameter("IsCross");
isCross = isCrossStr.equals("true") ? true : false;
// System.out.println(isCrossStr);
}
@Override
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", ConstantUtils.CROSS_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"); // 设置cookie
httpServletResponse.setHeader("XDomainRequestAllowed", "1");
}
chain.doFilter(request, response);
}
@Override
public void destroy() {
isCross = false;
}
}
二:在web.xml中配置如下
SimpleCORSFilter
com.fyq.filter.CorsFilter
IsCross
true
SimpleCORSFilter
/*
三:在spring-mvc.xml中配置如下。
allowed-origins="*"
allowed-methods="POST, GET, OPTIONS, DELETE, PUT"
allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
allow-credentials="true" />
注意:
一:有个比较坑的问题,可能你这样设置后还是无法解决跨域问题。如果你的请求是这样写的,那么恭喜你中奖了,还是无法解决跨域问题。@RequestMapping(value="/userlogin", method=RequestMethod.GET)
正确的写法如下:@RequestMapping("/userlogin")
不能指定请求的类型,具体原因我没想太明白。希望能帮忙到各位小伙伴们。
二:这样设置后,解决了跨域问题,但是如果是ajax请求的话,无法从session中获取到值。如登录后将用户的信息放入到session里面,但是你却无法获取到session里面的值,解决办法如下。加上xhrFields:{withCredentials:true},crossDomain:true即可。$.ajax({
type:"post",
xhrFields:{withCredentials:true},
crossDomain:true,
url:"",
data:"",
success: function(data){
}
})