允许跨域访问的过滤器
程序员文章站
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
sudo docker run -p 80:8080 swaggerapi/swagger-ui
然后不知道把想显示的json传上去,所以只好又起了个服务,用来提供json让swagger-ui,这时就需要解决跨域问题了。
上一篇: ps2018怎么没有切片
下一篇: 深入理解Java设计模式之单例模式