zoukankan      html  css  js  c++  java
  • 使用过滤器进行跨域

    项目图

    第一步:

    创建好过滤器后有两种方式获取跨域限制内容

    方式一:在web中配置好param-name,直接获取param-value

    package com.wbg.test01;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    @WebFilter(filterName = "CorsFilter")
    public class CorsFilter implements Filter {
        String[] originAll = null;
    
        @Override
        public void init(FilterConfig config) throws ServletException {
            String origin=config.getInitParameter("origin");
            if(origin!=null && !origin.isEmpty()){
                originAll = origin.split(",");
            }
        }
    
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
            String origin = request.getHeader("Origin");
            if (origin != null && !origin.isEmpty()){
                for (String originAlls : originAll) {
                        if(originAlls.equals("*")||originAlls.equals(origin)){
                            response.setHeader("Access-Control-Allow-Origin",origin);
                        }
                }
            }
                chain.doFilter(req, resp);
        }
    
        public void destroy() {
        }
    }
    View Code

    方式二:使用配置文件获取

     首先创建好配置文件

    origin=http://localhost:7070, http://localhost:8080, http://localhost:9090

    然后进行获取即可

    package com.wbg.test01;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebFilter;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Properties;
    
    @WebFilter(filterName = "CorsFilter")
    public class CorsFilter implements Filter {
        String[] originAll = null;
    
        @Override
        public void init(FilterConfig config) throws ServletException {
        }
    
        public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
            HttpServletRequest request = (HttpServletRequest) req;
            HttpServletResponse response = (HttpServletResponse) resp;
            //new一个读取配置文件
            Properties properties=new Properties();
            //获取文件路径
            String path=request.getServletContext().getRealPath("/dom.properties");
            //读取文件内容
            properties.load(new FileInputStream(path));
            //获取origin的value
            String originValue=properties.getProperty("origin");
            if(originValue!=null && !originValue.isEmpty()){
                originAll = originValue.split(",");
            }
           String origin = request.getHeader("Origin");
            if (origin != null && !origin.isEmpty()){
                for (String originAlls : originAll) {
                        if(originAlls.equals("*")||originAlls.equals(origin)){
                            response.setHeader("Access-Control-Allow-Origin",origin);
                        }
                }
            }
                chain.doFilter(req, resp);
        }
    
        public void destroy() {
        }
    }
    View Code

    第二步:创建servlet

    package com.wbg.test01;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    @WebServlet("/OriginServlet")
    public class OriginServlet extends HttpServlet {
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            PrintWriter writer=response.getWriter();
            writer.write("hello,word!");
        }
    }
    View Code

    第三步:配置web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
        <!--定义过滤器-->
        <filter>
            <!--定义过滤器拦截URL地址-->
            <filter-name>corsFilter</filter-name>
            <!--过滤器的文件-->
            <filter-class>com.wbg.test01.CorsFilter</filter-class>
            <!--在过滤文件中FilterConfig.getInitParameter(param-name)获取param-value-->
            <init-param>
               <!-- 名称key-->
                <param-name>origin</param-name>
                <!-- 定义value值-->
              <param-value>http://localhost:7070, http://localhost:8080, http://localhost:9090</param-value>
                <!-- 所有请求-->
                <!--  <param-value>*</param-value>-->
            </init-param>
        </filter>
        <filter-mapping>
            <!--过滤器的名称-->
            <filter-name>corsFilter</filter-name>
            <!--过滤器负责拦截的URL-->
            <!-- /* 会把所有的请求拦截下来 -->
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    </web-app>
    View Code

     demo:https://github.com/weibanggang/CorsFilter.git

  • 相关阅读:
    如何使用Total Recorder录制软件发出的声音
    火狐浏览器Firefox如何使用插件,火狐有哪些好用的插件
    [Tools] Create a Simple CLI Tool in Node.js with CAC
    [Unit Testing] Mock a Node module's dependencies using Proxyquire
    [SCSS] Create a gradient with a Sass loop
    [Algorithm] Heap data structure and heap sort algorithm
    [Debug] Diagnose a Slow Page Using Developer Tools
    [Tools] Deploy a Monorepo to Now V2
    [PWA] Add Push Notifications to a PWA with React in Chrome and on Android
    [Algorithms] Using Dynamic Programming to Solve longest common subsequence problem
  • 原文地址:https://www.cnblogs.com/weibanggang/p/10025652.html
Copyright © 2011-2022 走看看