SpringBoot中添加拦截器对流操作以后,在控制层再次获取流就会提示异常。

Date:2021-09-01

 

思路:使用适配器模式,如下:

package com.cms.filter;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class MyRequestWrapper extends HttpServletRequestWrapper {

private final String body;


public MyRequestWrapper(HttpServletRequest request) throws IOException {
super(request);
this.body = RequestReadUtils.read(request);
}

public String getBody() {
return body;
}



@Override
public ServletInputStream getInputStream() {
final ByteArrayInputStream bais = new ByteArrayInputStream(body.getBytes());
return new ServletInputStream() {

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

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

@Override
public void setReadListener(ReadListener readListener) {

}

@Override
public int read(){
return bais.read();
}
};
}

@Override
public BufferedReader getReader(){
return new BufferedReader(new InputStreamReader(this.getInputStream()));
}


}

package com.cms.filter;


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

public class RequestReadUtils {

private static final int BUFFER_SIZE = 1024 * 8;

public static String read(HttpServletRequest request) throws IOException {
BufferedReader bufferedReader = request.getReader();
StringWriter writer = new StringWriter();
write(bufferedReader,writer);
return writer.getBuffer().toString();
}

public static long write(Reader reader, Writer writer) throws IOException {
return write(reader, writer, BUFFER_SIZE);
}

public static long write(Reader reader, Writer writer, int bufferSize) throws IOException
{
int read;
long total = 0;
char[] buf = new char[bufferSize];
while( ( read = reader.read(buf) ) != -1 ) {
writer.write(buf, 0, read);
total += read;
}
return total;
}
}
最后使用getBody()获取前端给的请求体数据。
注意的事项:在Filter的FilterChain需要传递的参数为(将request进行包装(装饰者模式)的request,response)。
如有问题 请指出

SpringBoot中添加拦截器对流操作以后,在控制层再次获取流就会提示异常。

上一篇:Ubuntu下deb包的安装方法 - kevinhg的博客 - 博客频道 - CSDN.NET


下一篇:转载:Ubuntu下deb包的安装方法