跟我学springboot(二十五)springboot-过滤器之拦截不需要走过滤器的链接使用方法

时间:2024-05-30 16:34:45

1.创建项目

springboot怎么创建不多说了,前面博客已经有讲解,下面是我们创建好的项目目录。
跟我学springboot(二十五)springboot-过滤器之拦截不需要走过滤器的链接使用方法

2.编写代码

过滤器可以指定我们排除的参数exclusions,我们把需要隔离的url统一封装在这里,然后在webconfig配置filterReg.addInitParameter(“exclusions”,"/gogo,/hello");就可以拦截这两个请求。比如访问:
http://172.30.13.100:8080/hello
http://172.30.13.100:8080/gogo
跟我学springboot(二十五)springboot-过滤器之拦截不需要走过滤器的链接使用方法

访问:http://172.30.13.100:8080/gohello
跟我学springboot(二十五)springboot-过滤器之拦截不需要走过滤器的链接使用方法

详细代码如下:

WebConfig.java

package com.example.config;

import com.example.filter.TokenFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.DispatcherType;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by dell-3020 on 2017/8/15.
 */
@Configuration
public class WebConfig {


    @Bean
    FilterRegistrationBean tokenFilter() {
        FilterRegistrationBean filterReg = new FilterRegistrationBean(new TokenFilter());
        //优先级
        filterReg.setOrder(70);
        filterReg.setDispatcherTypes(DispatcherType.REQUEST);
        //匹配路径
        List<String> urlPatterns = new ArrayList<>();
//        urlPatterns.add("/*");
        filterReg.addUrlPatterns("/*");
        filterReg.addInitParameter("exclusions","/gogo,/hello");
//        filterReg.setUrlPatterns(urlPatterns);
        System.out.println("====来了");
        return filterReg;
    }
}

TestController

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * <br>类 名: TestController
 * <br>描 述: TODO
 * <br>作 者: lipeng
 * <br>创 建: 2018/9/29 17:34
 * <br>版 本:v1.0.0
 * <br>
 * <br>历 史: (版本) 作者 时间 注释
 */
@Controller
public class TestController {

    @ResponseBody
    @RequestMapping("/hello")
    public String go(){
        return "go";
    }
    @ResponseBody
    @RequestMapping("/gogo")
    public String gogo(){
        return "go";
    }
}

TokenFilter

package com.example.filter;

import com.example.util.PatternMatcher;
import com.example.util.ServletPathMatcher;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * <br>类 名: TokenFilter
 * <br>描 述: TODO
 * <br>作 者: lipeng
 * <br>创 建: 2018/9/29 17:32
 * <br>版 本:v1.0.0
 * <br>
 * <br>历 史: (版本) 作者 时间 注释
 */
public class TokenFilter implements Filter {


    public static final String PARAM_NAME_EXCLUSIONS = "exclusions";
    private Set<String> excludesPattern;
    protected String contextPath;
    protected PatternMatcher pathMatcher = new ServletPathMatcher();

    public String getContextPath() {
        return contextPath;
    }

    public void setContextPath(String contextPath) {
        this.contextPath = contextPath;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String param = filterConfig.getInitParameter(PARAM_NAME_EXCLUSIONS);
        if (param != null && param.trim().length() != 0) {
            this.excludesPattern = new HashSet(Arrays.asList(param.split("\\s*,\\s*")));
        }

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest)servletRequest;
        HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;
        TokenFilter.StatHttpServletResponseWrapper responseWrapper = new TokenFilter.StatHttpServletResponseWrapper(httpResponse);
        String requestURI = this.getRequestURI(httpRequest);
        if (this.isExclusion(requestURI)) {
            //不过滤走
            System.out.println("===不进过滤器");
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            //这里是过滤方法
            System.out.println("===进了过滤器");
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }

    public boolean isExclusion(String requestURI) {
        if (this.excludesPattern == null) {
            return false;
        } else {
            if (this.contextPath != null && requestURI.startsWith(this.contextPath)) {
                requestURI = requestURI.substring(this.contextPath.length());
                if (!requestURI.startsWith("/")) {
                    requestURI = "/" + requestURI;
                }
            }

            Iterator i$ = this.excludesPattern.iterator();

            String pattern;
            do {
                if (!i$.hasNext()) {
                    return false;
                }

                pattern = (String)i$.next();
            } while(!this.pathMatcher.matches(pattern, requestURI));

            return true;
        }
    }

    public static final class StatHttpServletResponseWrapper extends HttpServletResponseWrapper implements HttpServletResponse {
        private int status = 200;

        public StatHttpServletResponseWrapper(HttpServletResponse response) {
            super(response);
        }

        @Override
        public void setStatus(int statusCode) {
            super.setStatus(statusCode);
            this.status = statusCode;
        }

        public void setStatus(int statusCode, String statusMessage) {
            super.setStatus(statusCode, statusMessage);
            this.status = statusCode;
        }

        @Override
        public void sendError(int statusCode, String statusMessage) throws IOException {
            super.sendError(statusCode, statusMessage);
            this.status = statusCode;
        }

        @Override
        public void sendError(int statusCode) throws IOException {
            super.sendError(statusCode);
            this.status = statusCode;
        }

        @Override
        public int getStatus() {
            return this.status;
        }
    }

    public String getRequestURI(HttpServletRequest request) {
        return request.getRequestURI();
    }
}

PatternMatcher

package com.example.util;

/**
 * <br>类 名: PatternMatcher
 * <br>描 述: TODO
 * <br>作 者: lipeng
 * <br>创 建: 2018/9/29 18:56
 * <br>版 本:v1.0.0
 * <br>
 * <br>历 史: (版本) 作者 时间 注释
 */
public interface PatternMatcher {
    boolean matches(String var1, String var2);
}

ServletPathMatcher

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.example.util;

public class ServletPathMatcher implements PatternMatcher {
    private static final ServletPathMatcher INSTANCE = new ServletPathMatcher();

    public ServletPathMatcher() {
    }

    public static ServletPathMatcher getInstance() {
        return INSTANCE;
    }

    public boolean matches(String pattern, String source) {
        if (pattern != null && source != null) {
            pattern = pattern.trim();
            source = source.trim();
            int start;
            if (pattern.endsWith("*")) {
                start = pattern.length() - 1;
                if (source.length() >= start && pattern.substring(0, start).equals(source.substring(0, start))) {
                    return true;
                }
            } else if (pattern.startsWith("*")) {
                start = pattern.length() - 1;
                if (source.length() >= start && source.endsWith(pattern.substring(1))) {
                    return true;
                }
            } else if (pattern.contains("*")) {
                start = pattern.indexOf("*");
                int end = pattern.lastIndexOf("*");
                if (source.startsWith(pattern.substring(0, start)) && source.endsWith(pattern.substring(end + 1))) {
                    return true;
                }
            } else if (pattern.equals(source)) {
                return true;
            }
            return false;
        } else {
            return false;
        }
    }
}

FiltertestApplication

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class FiltertestApplication {

    public static void main(String[] args) {
        SpringApplication.run(FiltertestApplication.class, args);
    }
}