1. 程式人生 > >Java CORS 和 跨域前端測試工具

Java CORS 和 跨域前端測試工具


import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author : YingZhang
 * @Description:
 * @Date : Create in 10:45 AM 11/1/2018
 */
@Component
@WebFilter(urlPatterns = "/*")
public class JavaCORS implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods","GET, OPTIONS, HEAD, PUT, POST");
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_ACCEPTED);
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

Spring 裡對於CORS:

在瀏覽器上開啟一個網站,F12後在console裡輸入

(function loadXMLDoc() {
                var xmlhttp;
                xmlhttp = new XMLHttpRequest();
                            xmlhttp.onreadystatecatechange = function() {
                }
                            xmlhttp.open("GET", "http://1.11.111.23:6088/event/list", true);
                            xmlhttp.withCredentials = true;
                            xmlhttp.send();
            })()