跨域请求问题:CORS

1、编写过滤器类:需要实现Filter接口,并重写三个方法:

(1)先设置字符编码:

request.setCharacterEncoding("utf-8");

response.setContentType("text/html;charset=utf-8");

(2)重写init、destroy、doFilter方法

public class TestFilter2 implements Filter {

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

      HttpServletResponse responseH = (HttpServletResponse) resp;
      // responseH.setHeader("Access-Control-Allow-Origin", "*");
      responseH.setHeader("Access-Control-Allow-Origin", "http://localhost:8090");
      responseH.setHeader("Access-Control-Allow-Credentials", "true");
      responseH.setHeader("Access-Control-Allow-Methods", "*");
      responseH.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
      responseH.setHeader("Access-Control-Expose-Headers", "*");

        chain.doFilter(req, resp);   //本行代码表示,如果还有其他的过滤器,就调用其他的过滤器,这一行代码必须写在DoFilter方法的最后面
    }

    public void init(FilterConfig config) throws ServletException {

    }
}
//给过滤器添加注解配置@WebFilter(filterName = "本类名",urlPatterns = "/*"),则不需要再去web.xml中注册了
//若不添加注解配置,则需要在web.xml中注册,才能使用:

<filter>
<filter-name>LocalFilter(过滤器名)</filter-name>
<filter-class>com.kuangchi.Green_Transport.filter.LocalFilter(过滤器类名)</filter-class>
</filter>
<filter-mapping>
<filter-name>LocalFilter</filter-name>
<url-pattern>/*</url-pattern>   <!--过滤的路径,*代表访问所有路径的时候都会先访问这个过滤器-->
</filter-mapping>

 

//以上此种过滤器中设置请求头属性并设置web.xml中过滤器的设置方法,适用于SpringMVC 4.2以下版本,如果是SpringMVC  4.2及以上版本,用下面的添加方法在MVC相关的配置类里就可以了

@configuration

public class WebConfig extends webMvcConfigurerAdapter{

  @override

  public void addCorsMapping (CorsRegistry registry){

    registry.addMapping("/**/*").allowedOrigins("*");

  }

}



posted on   黑子菜园  阅读(223)  评论(0编辑  收藏  举报

编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 上周热点回顾(3.3-3.9)
· AI 智能体引爆开源社区「GitHub 热点速览」

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示