zoukankan      html  css  js  c++  java
  • 跨域请求问题: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("*");

      }

    }



  • 相关阅读:
    MySQL错误 1030-Got error 28 from storage engine
    电脑开机无反应 不显示BIOS 硬件没问题
    python错误 import: unable to open X server
    Python 错误 invalid command 'bdist_wheel' & outside environment /usr
    Cento 7安装 Failed to execute /init
    笔记《鸟哥的Linux私房菜》5 首次登入与在线求助 man
    Scrapy XPath语法
    Linux 用户操作
    Mysql 表修改
    Ubuntu 配置 Python环境 IPython
  • 原文地址:https://www.cnblogs.com/blackdd/p/8650676.html
Copyright © 2011-2022 走看看