ajax跨域访问方法

一、新建一个java类实现javax.servlet.Filter接口在重写方法doFilter里面加入关健的一句

response.setHeader("Access-Control-Allow-Origin", "*”);具体如下:

public class SimpleCORSFilter implements Filter{
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) arg1; 
        res.setHeader("Access-Control-Allow-Origin", "*"); 
        //如果要保持session就设置下面的
        HttpServletRequest request=(HttpServletRequest)arg0;
        res.setContentType("textml;charset=UTF-8");
        res.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        res.setHeader("Access-Control-Max-Age", "0");
        res.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");
        res.setHeader("Access-Control-Allow-Credentials", "true");
        res.setHeader("XDomainRequestAllowed","1");
        arg2.doFilter(arg0, arg1); 
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}

二、在web.xml 里面配制filter,如下:

  
    cors 
    包名.SimpleCORSFilter 
  
  
    cors 
    /*
  

三、 ajax跨域访问Session保持,在ajax 请求是也要加相应的代码

$.ajax({
url:url,
//加上这句话
xhrFields: {
           withCredentials: true
       },
       crossDomain: true,

success:function(result){
alert("test");
},
error:function(){
}
});

你可能感兴趣的:(ajax跨域访问方法)