Ajax跨域设置Access-Control-Allow-Origin

方法一:部分跨域

在需要跨域的Controller上添加注解

@CrossOrigin(origins = "*", maxAge = 3600)

方法二:全局跨域

1、新建类

import javax.servlet.*;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

public class CorsFilter implements Filter {

@Override

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) {

try {

HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;

            httpResponse.addHeader("Access-Control-Allow-Origin", "*");

            filterChain.doFilter(servletRequest, servletResponse);

        }catch (IOException e) {

e.printStackTrace();

        }catch (ServletException e) {

e.printStackTrace();

        }

}

}

2、在web.xml添加标签



        CorsFilter

                        

       com.taobao.controller.CorsFilter

    

    

        CorsFilter

        /*

    

你可能感兴趣的:(Ajax跨域设置Access-Control-Allow-Origin)