package com.example.ghs.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
/**
* @description:
* @author: yang_kai
* @date: 2020/11/14
*/
@Component
@Slf4j
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
//跨域设置,谁来都放行,与设置成*效果相同,但是这里设置成*行不通,因此用该方法代替
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
response.setHeader("Access-Control-Allow-Credentials", "true");
//不能设置成*,否则跨域请求会失败
response.setHeader("Access-Control-Allow-Methods", "POST,PUT, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
//我这里需要放行这三个header头部字段
response.setHeader("Access-Control-Allow-Headers", "content-type,x-requested-with,token");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
try {
String sessionId = request.getSession().getId();
if(!sessionId.equals(request.getSession().getAttribute("sessionId"))){
log.info("这是一个新的session");
request.getSession().setAttribute("sessionId",sessionId);
//初始化session
String projectUrl = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
request.getSession().setAttribute("sessionId",request.getSession().getAttribute("sessionId"));
request.getSession().setAttribute("contextPath",projectUrl);
}else {}
chain.doFilter(request, response);
} catch (Exception e) {
}
}
}
测试跨域
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://xxx:xxx/system/findTestPage');
xhr.send(null);
xhr.onload = function(e) {
var xhr = e.target;
console.log(xhr.responseText);
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://xxx:xxx/system/findTestPage');
xhr.send(null);
xhr.onload = function(e) {
var xhr = e.target;
console.log(xhr.responseText);
}