首先我们考虑后端是够允许跨域请求,
本人编写了一个过滤器代码如下:
package com.rbac.filter;
import java.io.IOException;
import java.io.OutputStream;
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 org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import com.rbac.aop.MessageExption;
/**
* 处理跨域的问题 处理非SpringSecurity处理之外的跨域请求
* @author admin
*
*/
@Component
public class OriginFilter implements Filter {
Log logger=LogFactory.getLog(OriginFilter.class);
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain arg2)
throws IOException, ServletException {
HttpServletResponse response=(HttpServletResponse)res;
HttpServletRequest request=(HttpServletRequest)req;
if (request.getMethod().equals("OPTIONS")) {
response.setStatus(HttpServletResponse.SC_OK);
}else{
arg2.doFilter(request, res);
}
String origin = request.getHeader("Origin");
System.out.println(origin);
// 浏览器 跨域 请求 Access-Control-Allow-Credentials 要设置为true 允许客户端携带跨域cookie, Access-Control-Allow-Origin 此时 origin值不能为“*”,只能为指定单一域名
//response.setH eader("Access-Control-Allow-Origin", "http://ailer.oicp.io");
response.setHeader("Access-Control-Allow-Origin", "*");// 允许指定域访问跨域资源
//是否允许cookie
//response.setHeader("Access-Control-Allow-Credentials", "true"); //
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "18000");//Access-Control-Max-Age用来指定本次预检请求的有效期,单位为秒,,在此期间不用发出另一条预检请求。
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
response.setHeader("Access-Control-Expose-Headers", "*");//响应客户端的头部 允许携带Token 等等
response.setContentType("application/json; charset=utf-8");
response.setCharacterEncoding("UTF-8");
logger.info("允许跨域");
try {
arg2.doFilter(req, res);
} catch (MessageExption e) {
response.setContentType("application/json; charset=utf-8");
response.setCharacterEncoding("UTF-8");
OutputStream out = response.getOutputStream();
String message=e.message;
out.write(message.getBytes("UTF-8"));
out.flush();
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
前端的代码也附上
$.ajax({ url:"http://127.0.0.1/authentication/form", timeout : 20000, type:"post", dataType:"json", data:{ username:"088358",password:"123" }, success:function(data,textStatus,xhr){ // 查看全部的 headers var headers=xhr.getAllResponseHeaders(); if(data.code="000000"){ alert('登录成功'); var headers=xhr.getAllResponseHeaders();//获取全部 后端返回的 参数 包括token console.log(headers); var authorization= xhr.getResponseHeader('Authorization')//获取token 名字你们自己定 console.log(authorization); localStorage.setItem('token',authorization); }else{ alert('登录失败'); } /* var token=xhr.getResponseHeader('Authorization'); localStorage.setItem('token',token);*/ }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert("1 异步调用返回失败,XMLHttpResponse.readyState:"+XMLHttpRequest.readyState); alert("2 异步调用返回失败,XMLHttpResponse.status:"+XMLHttpRequest.status); alert("3 异步调用返回失败,textStatus:"+textStatus); alert("4 异步调用返回失败,errorThrown:"+errorThrown); } })