欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springMVC解决跨域请求

程序员文章站 2022-07-08 14:39:49
...

1、创建Java类

package com.util;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

public class CrossFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
            HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        // if (request.getHeader("Access-Control-Request-Method") != null &&
        // "OPTIONS".equals(request.getMethod())) {
        // CORS "pre-flight" request
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods",
                "GET, POST, PUT, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "Content-Type");
        response.addHeader("Access-Control-Max-Age", "1800");// 30 min
        // }
        filterChain.doFilter(request, response);
    }

}

1、配置web.xml
<filter>
    <filter-name>cors</filter-name>
    <filter-class>com.util.CrossFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>cors</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

此时,option请求被CrossFilter过滤器接入并赋予跨域响应头,同时也进入FrameworkServlet中的doOption方法。查看浏览器控制台,发现option请求返回支持跨域信息,后续的post请求进入controller。