Java前后端分离跨域问题解决

  • 作者: 凯哥Java(公众号:凯哥Java)
  • 工作小总结
  • 时间:2020-11-18 10:09
  • 3376人已阅读
简介 现在越来越流行了前后端分离,但是前后端分离后,有个问题,就是跨域问题。怎么解决呢?1:创建crossFilter:import lombok.extern.slf4j.Slf4j;import org.apache.commons.httpclient.HttpStatus;import org.apache.commons.lang3.StringUtils;imp

🔔🔔🔔好消息!好消息!🔔🔔🔔

有需要的朋友👉:联系凯哥 微信号 kaigejava2022

现在越来越流行了前后端分离,但是前后端分离后,有个问题,就是跨域问题。怎么解决呢?

1:创建crossFilter:

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
 
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
 
/**
 * 解决跨域问题
 *
 * @Author kaigejava
 * @date 2020-11-17 15:25
 */
@Slf4j
@Component
public class CrossFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String plantformURl = "允许访问的链接。可以理解为白名单";
        String originHeads = request.getHeader("Origin");
        String uri = request.getRequestURI();
        String url = request.getRequestURL().toString();
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "0");
        response.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,Authorization,SessionToken,JSESSIONID,token");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("XDomainRequestAllowed", "1");
        if ("OPTIONS".equals(request.getMethod())) {
            response.setStatus(HttpStatus.SC_NO_CONTENT);
            return;
        }
        filterChain.doFilter(request, response);
    }
 
    public static String getRefererUrl(HttpServletRequest request) {
        String returnValue = null;
        if (request != null && !StringUtils.isEmpty(request.getHeader("Referer"))) {
            returnValue = request.getHeader("Referer");
            String[] urls = returnValue.split("/");
            if (urls != null && urls.length > 3) {
                returnValue = urls[0] + "//" + urls[2];
            }
        }
        return returnValue;
    }
 
    @Override
    public void destroy() {
    }
}

需要注意,必须配置:

if ("OPTIONS".equals(request.getMethod())) {
    response.setStatus(HttpStatus.SC_NO_CONTENT);
    return;
}

详细原因参见:Java后端跨域之http预请求options

配置myFilterConfig

import com.kaigejava.filter.CrossFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 
@Configuration
public class MyFilterConfig {
    @Autowired
    private CrossFilter crossFilter;
 
    @Bean
    public FilterRegistrationBean registerAuthFilter() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(crossFilter);
        registration.addUrlPatterns("/*");
        registration.setName("crossFilter");
        registration.setOrder(1);  //值越小,Filter越靠前。
        return registration;
    }
}


TopTop