springboot项目使用过滤器统一进行参数校验,敏感词替换

  • 1.问题场景
    • 对入参进行敏感词过滤,去空格,去换行符等操作,可提高程序健壮性,减少由此带来的业务上的bug,是很普遍的需求。使用过滤器统一,不用每个接口进行处理,提高代码可维护性
      • springboot项目使用过滤器统一进行参数校验,敏感词替换_第1张图片
  • 2.实现自定义ServletInputStream(只对post类型)获取流,校验并json参数,把去掉过滤参数后的参数传递回去
  • 3.实现自定义 HttpServletRequestWrapper
    • package com.pld.content.manager.common;
      
      import com.alibaba.fastjson.JSON;
      import com.alibaba.fastjson.JSONArray;
      import com.alibaba.fastjson.JSONObject;
      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.ReadListener;
      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 tlj
       * @date 2019/8/5
       */
      
      public class ParameterRequestWrapper extends HttpServletRequestWrapper {
      
          private Map params = new HashMap<>();
      
          public ParameterRequestWrapper(HttpServletRequest request) {
              // 将request交给父类,以便于调用对应方法的时候,将其输出,其实父亲类的实现方式和第一种new的方式类似
              super(request);
              //将参数表,赋予给当前的Map以便于持有request中的参数
              Map requestMap=request.getParameterMap();
              this.params.putAll(requestMap);
          }
          /**
           * 重写getInputStream方法  post类型的请求参数必须通过流才能获取到值
           */
          @Override
          public ServletInputStream getInputStream() throws IOException {
              // 非json类型,直接返回
              if(!super.getHeader(HttpHeaders.CONTENT_TYPE).equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)){
                  return super.getInputStream();
              }
              //为空,直接返回
              String json = IOUtils.toString(super.getInputStream(), "utf-8");
              if (StringUtils.isEmpty(json)) {
                  return super.getInputStream();
              }
              Map map = JSON.parseObject(json);
              dealMap(map);
              ByteArrayInputStream bis = new ByteArrayInputStream(JSON.toJSONString(map).getBytes("utf-8"));
              return new MyServletInputStream(bis);
          }
      
          private void dealMap( Map map ){
              Set set = map.keySet();
              Iterator it=set.iterator();
              // 将parameter的值去除空格后重写回去
              while(it.hasNext()){
                  String key= it.next();
                  Object values = map.get(key);
                  if (values instanceof String) {
                      values = ((String) values).trim();
                  }else if (values instanceof JSONArray){
                      JSONArray json = (JSONArray) values;
                      if(!json.isEmpty()){
                          for(int i=0;i> iterator = jsonObject.entrySet().iterator();
              while(iterator.hasNext()) {
                  Map.Entry entry =  iterator.next();
                  String key = entry.getKey();
                  Object values = entry.getValue();
                  if (values instanceof String) {
                      values = ((String) values).trim();
                  }
                  jsonObject.put(key, values);
              }
          }
      
          public static void main(String[] args) {
              JSONObject jsonObject = new JSONObject();
              jsonObject.put("k1","v1");
              Iterator> iterator = jsonObject.entrySet().iterator();
              while(iterator.hasNext()) {
                  Map.Entry entry =  iterator.next();
                  entry.getValue();
                  entry.getKey();
              }
      
      
          }
          /**
           * 重写getParameter 参数从当前类中的map获取
           */
          @Override
          public String getParameter(String name) {
              String[]values = params.get(name);
              if(values == null || values.length == 0) {
                  return null;
              }
              return values[0];
          }
          /**
           * 重写getParameterValues
           */
          public String[] getParameterValues(String name) {//同上
              return params.get(name);
          }
      
          class MyServletInputStream extends  ServletInputStream{
              private ByteArrayInputStream bis;
              public MyServletInputStream(ByteArrayInputStream bis){
                  this.bis=bis;
              }
              @Override
              public boolean isFinished() {
                  return true;
              }
      
              @Override
              public boolean isReady() {
                  return true;
              }
      
              @Override
              public void setReadListener(ReadListener listener) {
                  //
              }
              @Override
              public int read() {
                  return bis.read();
              }
          }
      }
      
  • 实现自定义Filter,过滤器配置
    • package com.pld.content.manager.common;
      
      import org.springframework.stereotype.Component;
      
      import javax.servlet.*;
      import javax.servlet.annotation.WebFilter;
      import javax.servlet.http.HttpServletRequest;
      import java.io.IOException;
      
      /**
       * @author tlj
       * @date 2019/8/5
       */
      
      
      @Component
      @WebFilter(urlPatterns = "/**", filterName = "ParamsFilter",dispatcherTypes=DispatcherType.REQUEST)
      public class ParamsFilter implements Filter {
      
      
          @Override
          public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
                  throws IOException, ServletException {
              ParameterRequestWrapper parmsRequest = new ParameterRequestWrapper((HttpServletRequest) arg0);
              arg2.doFilter(parmsRequest, arg1);
          }
      
          @Override
          public void destroy() {
      
          }
      
          @Override
          public void init(FilterConfig arg0) {
      
          }
      
      
      }

       

你可能感兴趣的:(代码记录,springboot,参数校验,过滤器)