springMVC解决跨域请求

1、创建类

package com.hzc.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);
    }

}

2、配置web.xml

<filter>
    <filter-name>corsfilter-name>
    <filter-class>com.hzc.util.CrossFilterfilter-class>
filter>
<filter-mapping>
    <filter-name>corsfilter-name>
    <url-pattern>/*url-pattern>
filter-mapping>

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

你可能感兴趣的:(spring)