欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

详解在Spring MVC或Spring Boot中使用Filter打印请求参数问题

程序员文章站 2022-03-06 23:37:11
使用spring mvc或spring boot中打印或记录日志一般使用aop记录request请求和response响应参数,在不使用aop的前提下,如果在filter中打印日志,在打印或消费请求类...

使用spring mvc或spring boot中打印或记录日志一般使用aop记录request请求和response响应参数,在不使用aop的前提下,如果在filter中打印日志,在打印或消费请求类型为content-type:application/json的请求时,会出现严重的问题。

在spring体系中,过滤器的定义我们一般采用继承onceperrequestfilter的方式,当然也可以使用原始的filter。

错误写法一:

如果不对request和response进行处理,使用伪代码采用如下写法打印请求和响应参数(注:此时request请求类型为post,接收的是json数据)

  @override
  protected void dofilterinternal(httpservletrequest request, httpservletresponse       
         response, filterchain filterchain) throws servletexception, ioexception {
    filterchain.dofilter(request, response);
    printrequestlog(request);
    printresonselog(response);
  }

运行测试后你会发现抛出如下异常: 

java.io.ioexception: stream closed
 at org.apache.catalina.connector.inputbuffer.read(inputbuffer.java:359) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.catalina.connector.coyoteinputstream.read(coyoteinputstream.java:132) ~[tomcat-embed-core-9.0.31.jar:9.0.31]
 at sun.nio.cs.streamdecoder.readbytes(streamdecoder.java:284) ~[na:1.8.0_191]
 at sun.nio.cs.streamdecoder.implread(streamdecoder.java:326) ~[na:1.8.0_191]
 at sun.nio.cs.streamdecoder.read(streamdecoder.java:178) ~[na:1.8.0_191]
 at java.io.inputstreamreader.read(inputstreamreader.java:184) ~[na:1.8.0_191]
 at java.io.bufferedreader.fill(bufferedreader.java:161) ~[na:1.8.0_191]
 at java.io.bufferedreader.readline(bufferedreader.java:324) ~[na:1.8.0_191]
 at java.io.bufferedreader.readline(bufferedreader.java:389) ~[na:1.8.0_191]
 at com.micro.backend.filter.loggingfilter.getbodystring(loggingfilter.java:60) [classes/:na]
 at com.micro.backend.filter.loggingfilter.dofilterinternal(loggingfilter.java:49) [classes/:na]
 at org.springframework.web.filter.onceperrequestfilter.dofilter(onceperrequestfilter.java:119) [spring-web-5.1.14.release.jar:5.1.14.release]
 at org.apache.catalina.core.applicationfilterchain.internaldofilter(applicationfilterchain.java:193) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.catalina.core.applicationfilterchain.dofilter(applicationfilterchain.java:166) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.springframework.web.filter.requestcontextfilter.dofilterinternal(requestcontextfilter.java:100) [spring-web-5.1.14.release.jar:5.1.14.release]
 at org.springframework.web.filter.onceperrequestfilter.dofilter(onceperrequestfilter.java:119) [spring-web-5.1.14.release.jar:5.1.14.release]
 at org.apache.catalina.core.applicationfilterchain.internaldofilter(applicationfilterchain.java:193) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.catalina.core.applicationfilterchain.dofilter(applicationfilterchain.java:166) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.springframework.web.filter.formcontentfilter.dofilterinternal(formcontentfilter.java:93) [spring-web-5.1.14.release.jar:5.1.14.release]
 at org.springframework.web.filter.onceperrequestfilter.dofilter(onceperrequestfilter.java:119) [spring-web-5.1.14.release.jar:5.1.14.release]
 at org.apache.catalina.core.applicationfilterchain.internaldofilter(applicationfilterchain.java:193) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.catalina.core.applicationfilterchain.dofilter(applicationfilterchain.java:166) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.springframework.web.filter.hiddenhttpmethodfilter.dofilterinternal(hiddenhttpmethodfilter.java:94) [spring-web-5.1.14.release.jar:5.1.14.release]
 at org.springframework.web.filter.onceperrequestfilter.dofilter(onceperrequestfilter.java:119) [spring-web-5.1.14.release.jar:5.1.14.release]
 at org.apache.catalina.core.applicationfilterchain.internaldofilter(applicationfilterchain.java:193) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.catalina.core.applicationfilterchain.dofilter(applicationfilterchain.java:166) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.springframework.web.filter.characterencodingfilter.dofilterinternal(characterencodingfilter.java:201) [spring-web-5.1.14.release.jar:5.1.14.release]
 at org.springframework.web.filter.onceperrequestfilter.dofilter(onceperrequestfilter.java:119) [spring-web-5.1.14.release.jar:5.1.14.release]
 at org.apache.catalina.core.applicationfilterchain.internaldofilter(applicationfilterchain.java:193) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.catalina.core.applicationfilterchain.dofilter(applicationfilterchain.java:166) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.catalina.core.standardwrappervalve.invoke(standardwrappervalve.java:202) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.catalina.core.standardcontextvalve.invoke(standardcontextvalve.java:96) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.catalina.authenticator.authenticatorbase.invoke(authenticatorbase.java:541) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.catalina.core.standardhostvalve.invoke(standardhostvalve.java:139) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.catalina.valves.errorreportvalve.invoke(errorreportvalve.java:92) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.catalina.core.standardenginevalve.invoke(standardenginevalve.java:74) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.catalina.connector.coyoteadapter.service(coyoteadapter.java:343) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.coyote.http11.http11processor.service(http11processor.java:367) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.coyote.abstractprocessorlight.process(abstractprocessorlight.java:65) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.coyote.abstractprotocol$connectionhandler.process(abstractprotocol.java:868) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.tomcat.util.net.nioendpoint$socketprocessor.dorun(nioendpoint.java:1639) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at org.apache.tomcat.util.net.socketprocessorbase.run(socketprocessorbase.java:49) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1149) [na:1.8.0_191]
 at java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:624) [na:1.8.0_191]
 at org.apache.tomcat.util.threads.taskthread$wrappingrunnable.run(taskthread.java:61) [tomcat-embed-core-9.0.31.jar:9.0.31]
 at java.lang.thread.run(thread.java:748) [na:1.8.0_191]

错误写法二:

如果不对request和response进行处理,使用伪代码采用如下写法打印请求和响应参数(注:此时request请求类型为post,接收的是json数据)

  @override
  protected void dofilterinternal(httpservletrequest request, httpservletresponse 
       response, filterchain filterchain) throws servletexception, ioexception {
    printrequestlog(request);
    printresonselog(response);
    filterchain.dofilter(request, response);
  }

运行测试后你会发现抛出如下异常:  

org.springframework.http.converter.httpmessagenotreadableexception: required request body is missing

遇到这样的问题你是不是有坐立不安、心烦意乱、百爪挠心的痛楚,不要着急,下面我给出一个解决方案。

首先我们使用装饰器模式,创建request和response两个包装类,如下:

import javax.servlet.readlistener;
import javax.servlet.servletinputstream;
import javax.servlet.servletrequest;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletrequestwrapper;
import java.io.*;
import java.nio.charset.charset;
/**
* @description:  请求包装器
* @author:     liuliya
* @createdate:   2020/4/29 10:00
*/
public class requestwrapper extends httpservletrequestwrapper {
  
  private final byte[] body;
 
  public requestwrapper(httpservletrequest request) throws ioexception {
    super(request);
    body = getrequestbodystring(request).getbytes(charset.defaultcharset());
  }
 
  @override
  public bufferedreader getreader() throws ioexception {
    return new bufferedreader(new inputstreamreader(getinputstream()));
  }
 
  @override
  public servletinputstream getinputstream() throws ioexception {
 
    final bytearrayinputstream bais = new bytearrayinputstream(body);
 
    return new servletinputstream() {
 
      @override
      public int read() throws ioexception {
        return bais.read();
      }
 
      @override
      public boolean isfinished() {
        return false;
      }
 
      @override
      public boolean isready() {
        return false;
      }
 
      @override
      public void setreadlistener(readlistener listener) {
 
      }
    };
  }
 
  public string getrequestbodystring(servletrequest request) {
    stringbuilder sb = new stringbuilder();
    inputstream inputstream = null;
    bufferedreader reader = null;
    try {
      inputstream = request.getinputstream();
      reader = new bufferedreader(new inputstreamreader(inputstream, charset.defaultcharset()));
      string line;
      while ((line = reader.readline()) != null) {
        sb.append(line);
      }
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      if (inputstream != null) {
        try {
          inputstream.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
      if (reader != null) {
        try {
          reader.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
    }
    return sb.tostring();
  }
}
package com.micro.backend.filter.support;
 
import org.apache.commons.io.output.teeoutputstream; 
import javax.servlet.servletoutputstream;
import javax.servlet.servletresponse;
import javax.servlet.writelistener;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpservletresponsewrapper;
import java.io.bytearrayoutputstream;
import java.io.ioexception;
import java.io.printwriter;
 
/**
 * @description: 响应包装器
 * @author: liuliya
 * @createdate: 2020/4/29 10:00
 */
public class responsewrapper extends httpservletresponsewrapper {
 
  private final bytearrayoutputstream bos = new bytearrayoutputstream();
  private printwriter writer = new printwriter(bos);
 
  public responsewrapper(httpservletresponse response) {
    super(response);
  }
 
  @override
  public servletresponse getresponse() {
    return this;
  }
 
  @override
  public servletoutputstream getoutputstream() throws ioexception {
    return new servletoutputstream() {
      @override
      public boolean isready() {
        return false;
      }
 
      @override
      public void setwritelistener(writelistener listener) {
 
      }
 
      private teeoutputstream tee = new teeoutputstream(responsewrapper.super.getoutputstream(), bos);
 
      @override
      public void write(int b) throws ioexception {
        tee.write(b);
      }
    };
  }
 
  @override
  public printwriter getwriter() throws ioexception {
    return new teeprintwriter(super.getwriter(), writer);
  }
 
  public byte[] tobytearray() {
    return bos.tobytearray();
  }
}
package com.micro.backend.filter.support;
import java.io.printwriter;
//printwriter是一种写入字符的一种操作类,可以写入字符,teeprintwriter继承了他,主要功能是把原始的字符流copy到branch里面。
public class teeprintwriter extends printwriter {
 
  printwriter branch;
 
  public teeprintwriter(printwriter main, printwriter branch) {
    super(main, true);
    this.branch = branch;
  }
 
  public void write(char buf[], int off, int len) {
    super.write(buf, off, len);
    super.flush();
    branch.write(buf, off, len);
    branch.flush();
  }
 
  public void write(string s, int off, int len) {
    super.write(s, off, len);
    super.flush();
    branch.write(s, off, len);
    branch.flush();
  }
 
  public void write(int c) {
    super.write(c);
    super.flush();
    branch.write(c);
    branch.flush();
  }
 
  public void flush() {
    super.flush();
    branch.flush();
  }
}

接下来创建最重要的loggingfilter类,继承onceperrequestfilter,或者直接继承servlet中原始的filter。

package com.micro.backend.filter;
 
import com.micro.backend.filter.support.requestwrapper;
import com.micro.backend.filter.support.responsewrapper;
import lombok.extern.slf4j.slf4j;
import org.springframework.context.annotation.configuration;
import org.springframework.web.filter.onceperrequestfilter;
 
import javax.servlet.filterchain;
import javax.servlet.servletexception;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import javax.servlet.http.httpsession;
import java.io.ioexception;
import java.io.unsupportedencodingexception;
 
/**
* @author:     liuliya
* @createdate:   2020/4/28 23:30
*/
@slf4j
@configuration
public class loggingfilter extends onceperrequestfilter {
  
  private static final string request_prefix_name = "request请求: ";
  private static final string response_prefix_name = "response请求: ";
 
  @override
  protected void dofilterinternal(httpservletrequest request, httpservletresponse response, filterchain filterchain) throws servletexception, ioexception {
    request = new requestwrapper(request);
    response = new responsewrapper(response);
    filterchain.dofilter(request, response);
    printrequestlog(request);
    printresponselog((responsewrapper) response);
  }
 
  private void printrequestlog(final httpservletrequest request) {
    stringbuilder msg = new stringbuilder();
    msg.append(request_prefix_name);
    httpsession session = request.getsession(false);
    if (session != null) {
      msg.append("sessionid = ").append(session.getid()).append("; ");
    }
    if (request.getmethod() != null) {
      msg.append("method = ").append(request.getmethod()).append("; ");
    }
    if (request.getcontenttype() != null) {
      msg.append("contenttype = ").append(request.getcontenttype()).append("; ");
    }
    msg.append("uri = ").append(request.getrequesturi());
    if (request.getquerystring() != null) {
      msg.append('?').append(request.getquerystring());
    }
 
    if (request instanceof requestwrapper && !ismultipart(request) && !isbinarycontent(request)) {
      requestwrapper requestwrapper = (requestwrapper) request;
      msg.append("; payload = ").append(requestwrapper.getrequestbodystring(request));
    }
    log.info(msg.tostring());
  }
 
  private boolean isbinarycontent(final httpservletrequest request) {
    if (request.getcontenttype() == null) {
      return false;
    }
    return request.getcontenttype().startswith("image")
        || request.getcontenttype().startswith("video")
        || request.getcontenttype().startswith("audio");
  }
 
  private boolean ismultipart(final httpservletrequest request) {
    return request.getcontenttype() != null
        && request.getcontenttype().startswith("multipart/form-data");
  }
 
  private void printresponselog(final responsewrapper response) {
    stringbuilder msg = new stringbuilder();
    msg.append(response_prefix_name);
    try {
      msg.append("; payload = ")
          .append(new string(response.tobytearray(), response.getcharacterencoding()));
    } catch (unsupportedencodingexception e) {
      log.warn("failed to parse response payload", e);
    }
    log.info(msg.tostring());
  } 
}

参考以上我整理出的代码,你就会发现奇迹!!!

为什么要这么写呢,其本质是把请求流拷贝了一份,一个供filterchain向下传递,一个来做流的消费,再有一个就是运用装饰器模式的精髓所在。

到此这篇关于详解在spring mvc或spring boot中使用filter打印请求参数问题的文章就介绍到这了,更多相关springboot filter打印请求参数内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!