zoukankan      html  css  js  c++  java
  • 跨域过滤器配置

    import java.io.IOException;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpServletRequest;
    
    /**
     * 跨域配置<br>
     * 跨域资源共享 CORS 详解:http://www.ruanyifeng.com/blog/2016/04/cors.html<br/>
     * HTTP 中文开发手册:https://www.php.cn/manual/view/35587.html
     */
    public class CrossFilter implements Filter {
    
        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chiain)
            throws IOException, ServletException {
    
            HttpServletRequest request = (HttpServletRequest)servletRequest;
            HttpServletResponse response = (HttpServletResponse)servletResponse;
    
            // 允许跨域的地址*表示所有
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:8848");
            // 表示是否允许发送Cookie
            response.setHeader("Access-Control-Allow-Credentials", "true");
            // 允许跨域的方法
            response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE");
            // 预检请求的有效期,OPTIONS请求就是想服务端进行探测支持的方法
            response.setHeader("Access-Control-Max-Age", "3600");
            // 跨域时允许的请求头字段
            response.setHeader("Access-Control-Allow-Headers",
                "Origin, X-Requested-With, Content-Type, Accept,Token,tokenzsk,tokenzsk1");
            // 检测时直接返回
            if ("OPTIONS".equals(request.getMethod())) {
                response.setStatus(HttpServletResponse.SC_NO_CONTENT);
                return;
            }
            chiain.doFilter(servletRequest, servletResponse);
        }
    }
    
    // 注册过滤器
    @Bean
    public FilterRegistrationBean<CrossFilter> corssFilterRegiste() {
        FilterRegistrationBean<CrossFilter> reFilter = new FilterRegistrationBean<>();
        // 创建并注册TestFilter
        reFilter.setFilter(new CrossFilter());
        // 拦截的路径(对所有请求拦截)
        reFilter.addUrlPatterns("/services/*");
        // 拦截器的名称
        reFilter.setName("CrossFilter");
        // 拦截器的执行顺序。数字越小越先执行
        reFilter.setOrder(1);
        return reFilter;
    }
  • 相关阅读:
    python初学第一节课
    关于float类型和u32类型问题
    今天的工作状态,规划未来一段时间内必须完成的事情(Record the working status of today,planning for the next period of time must be completed)
    STM32 硬件I2C初始化 I2C1_GPIO_AF_Config
    C语言编程规范--------12 宏
    C语言编程规范--------11 代码测试、维护
    C语言编程规范--------10 代码编辑、编译、审查
    C语言编程规范--------9 质量保证
    C语言编程规范--------8 效率
    C语言编程规范--------7 可测性
  • 原文地址:https://www.cnblogs.com/zincredible/p/14196881.html
Copyright © 2011-2022 走看看