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

Spring全局开启跨域

程序员文章站 2022-03-10 13:27:54
...

使用Filter方式来开启跨域拦截
web.xml 文件配置:

	<!--统一开启跨域拦截-->
	<filter>
		<filter-name>crosFilter</filter-name>
		<filter-class>xxxx.SysCorsFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>crosFilter</filter-name>
		<url-pattern>/*</url-pattern>
		<dispatcher>REQUEST</dispatcher>
	</filter-mapping>

编写过滤类:

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

public class SysCorsFilter implements Filter {
    private FilterConfig filterConfig = null;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) 
    	throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        response.addHeader("Access-Control-Allow-Headers", "origin,accept,content-type");
        response.setHeader("Access-Control-Allow-Origin", "*");
        chain.doFilter(request, response);
    }
    @Override
    public void destroy() {
        filterConfig = null;
    }
}

全局设置的话,颗粒度比较粗,但是可以统一开启和统一关闭。
在开发过程中需要用到的跨域,但是实际线上的项目不需要进行跨域,所以为了方便设置了全局跨域。

相关标签: Filter