SpringBoot过滤器(过滤请求参数)

包结构


paramsfilter.png
  1. 创建ParamsFilter实现Filter接口
package com.example.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author chengdongyi
 * @description: 请求参数过滤器
 * @date 2019/7/1 10:33
 */
public class ParamsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

        ParamsRequestWrapper requestWrapper = new ParamsRequestWrapper(httpRequest);
        filterChain.doFilter(requestWrapper, servletResponse);

    }

    @Override
    public void destroy() {

    }

}
  1. 过滤请求参数
package com.example.filter;

import com.alibaba.fastjson.JSON;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * @author chengdongyi
 * @description: 对请求参数进行过滤
 * @date 2019/7/1 11:02
 */
public class ParamsRequestWrapper extends HttpServletRequestWrapper {

    private Map params = new HashMap<>();
    private static final String ENCODING = "UTF-8";
    private static final String CLASSTYPE = "java.lang.String";

    public ParamsRequestWrapper(HttpServletRequest request) {
        super(request);
        // 将参数表,赋予给当前的Map以便于持有request中的参数
        Map requestMap = request.getParameterMap();
        System.out.println("转化前参数:" + JSON.toJSONString(requestMap));
        this.params.putAll(requestMap);
        this.modifyParameters();
        System.out.println("转化后参数:" + JSON.toJSONString(params));
    }


    /**
     * 重写getInputStream方法  post请求参数必须通过流才能获取到值
     */
    @Override
    public ServletInputStream getInputStream() throws IOException {

        ServletInputStream stream = super.getInputStream();

        //非json类型,直接返回
        if (!super.getHeader(HttpHeaders.CONTENT_TYPE).equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
            return stream;
        }
        String json = IOUtils.toString(stream, ENCODING);

        if (StringUtils.isBlank(json)) {
            return stream;
        }

        System.out.println("转化前参数:" + json);
        Map map = modifyParams(json);
        System.out.println("转化后参数:" + JSON.toJSONString(map));

        ByteArrayInputStream bis = new ByteArrayInputStream(JSON.toJSONString(map).getBytes(ENCODING));

        return new ParamsServletInputStream(bis);
    }

    private static Map modifyParams(String json) {

        Map params = JSON.parseObject(json);
        Map maps = new HashMap<>(params.size());
        for (String key : params.keySet()) {
            Object value = getValue(params.get(key));
            maps.put(key, value);
        }
        return maps;
    }

    private static Object getValue(Object obj) {

        if (obj == null) {
            return null;
        }
        String type = obj.getClass().getName();
        // 对字符串的处理
        if (CLASSTYPE.equals(type)) {
            obj = obj.toString().trim();
        }
        return obj;
    }

    /**
     * 将parameter的值去除空格后重写回去
     */
    private void modifyParameters() {
        Set set = params.keySet();
        Iterator it = set.iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            String[] values = params.get(key);
            values[0] = values[0].trim();
            params.put(key, values);
        }
    }

    /**
     * 重写getParameter 参数从当前类中的map获取
     */
    @Override
    public String getParameter(String name) {
        String[] values = params.get(name);
        if (values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

}
  1. 字节数据转换流(Map → ByteArrayInputStream → ServletInputStream )
package com.example.filter;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * @author chengdongyi
 * @description: 请求参数输入流
 * @date 2019/7/1 10:46
 */
public class ParamsServletInputStream extends ServletInputStream {

    private ByteArrayInputStream bis;

    public ParamsServletInputStream(ByteArrayInputStream bis) {
        this.bis = bis;
    }

    @Override
    public boolean isFinished() {
        return true;
    }

    @Override
    public boolean isReady() {
        return true;
    }

    @Override
    public void setReadListener(ReadListener readListener) {

    }

    @Override
    public int read() throws IOException {
        return bis.read();
    }

}
  1. 过滤器配置类
package com.example.config;

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

import javax.servlet.DispatcherType;

/**
 * @description: 过滤器配置类
 * @author chengdongyi
 * @date 2019/7/1 10:31
 */
@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean parmsFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new ParamsFilter());
        registration.addUrlPatterns("/*");
        registration.setName("ParamsFilter");
        registration.setOrder(Integer.MAX_VALUE - 1);
        return registration;
    }

}




过滤器过滤的请求为所有请求(/*),排除部分请求

  1. 在配置类中添加不需要过滤的请求的url
package com.example.config;

import com.example.filter.ParamsFilter;
import org.apache.commons.lang3.StringUtils;
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.HashSet;
import java.util.Set;

/**
 * @description: 过滤器配置类
 * @author chengdongyi
 * @date 2019/7/1 10:31
 */
@Configuration
public class FilterConfig {

    @Bean
    public FilterRegistrationBean parmsFilterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new ParamsFilter());
        registration.addUrlPatterns("/*");

        // 排除不需要过滤的请求
        Set set = new HashSet<>();
        set.add("/hello");
        set.add("/testFilter");
        String urls = StringUtils.join(set.toArray(), ",");
        registration.addInitParameter("exclusions", urls);
        registration.setName("ParamsFilter");
        registration.setOrder(Integer.MAX_VALUE - 1);
        return registration;
    }

}
package com.example.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author chengdongyi
 * @description: 请求参数过滤器
 * @date 2019/7/1 10:33
 */
public class ParamsFilter implements Filter {

    public static final String PARAM_NAME_EXCLUSIONS = "exclusions";
    public static final String SEPARATOR = ",";
    private Set excludesUrls;

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

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;

        String requestURI = httpRequest.getRequestURI();

        if (this.isExclusion(requestURI)) {
            // 不过滤
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            // 过滤
            ParamsRequestWrapper requestWrapper = new ParamsRequestWrapper(httpRequest);
            filterChain.doFilter(requestWrapper, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }

    public boolean isExclusion(String requestURI) {

        if (this.excludesUrls == null) {
            return false;
        }

        for (String url : this.excludesUrls) {
            if (url.equals(requestURI)) {
                return true;
            }
        }
        return false;
    }

}

GitHub:https://github.com/chengdongyi/paramsfilter

你可能感兴趣的:(SpringBoot过滤器(过滤请求参数))