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

允许跨域访问的过滤器

程序员文章站 2022-03-24 10:21:11
...

在web.xml文件中加入一个过滤器:

<filter>
		<filter-name>CorsFilter</filter-name>
		<filter-class>cn.test.CorsFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>CorsFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

 过滤器如下

package cn.test;

import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
 
public class CorsFilter implements Filter {
 
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
 
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
       System.out.println("允许跨域");
    	HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        httpResponse.addHeader("Access-Control-Allow-Origin", "*");
        httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        httpResponse.setHeader("Access-Control-Allow-Methods", "GET, PUT, DELETE, POST");
        filterChain.doFilter(servletRequest, servletResponse);
    }
 
    @Override
    public void destroy() {
 
    }
}

 因为今天装了个swaggerapi/swagger-ui,装的docker镜像

写道
sudo docker pull swaggerapi/swagger-ui
sudo docker run -p 80:8080 swaggerapi/swagger-ui

 然后不知道把想显示的json传上去,所以只好又起了个服务,用来提供json让swagger-ui,这时就需要解决跨域问题了。