我在服务器端添加了cors过滤器,用于休息api交叉原始请求。添加过滤器后,我的会话管理无法在应用程序中运行。它在每个请求中创建一个新会话,因此我的应用程序无法正常工作。任何人都可以建议如何在spring
中使用会话管理实现cors过滤器。
public class CORSFilter extends OncePerRequestFilter {
private static final Log LOG = LogFactory.getLog(CORSFilter.class);
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
HttpSession session = request.getSession();
if(session.isNew()){
LOG.info("New session is jutst created");
session.setAttribute("SESSIONID", session.getId());
LOG.info("new session id..."+session.getId());
}else{
LOG.info("This is old session");
}
String origin = request.getHeader("Origin");
String method=request.getMethod();
System.out.println("method id " +method);
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
LOG.info("Sending Header....");
// CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
response.addHeader("Access-Control-Allow-Headers", "Authorization");
response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
response.addHeader("Access-Control-Max-Age", "3600");
}
filterChain.doFilter(request, response);
}
}
请求标题
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate
Accept-Language:en-US,en;q=0.8
Connection:keep-alive
Content-Length:57
Content-Type:text/plain;charset=UTF-8
Host:localhost:8080
Origin:http://localhost:8081
Referer:http://localhost:8081/
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36