gpt4 book ai didi

java - HttpServletRequestWrapper,setReadListener/isFinished/isReady 的示例实现?

转载 作者:IT老高 更新时间:2023-10-28 13:47:14 24 4
gpt4 key购买 nike

我正在尝试调整 HttpServletRequestWrapper(参见 How to read InputStream multiple times),以便在过滤器中使用 HTTP Post 正文后能够读取它。现在我遇到了如何实现 ServletInputStream 的挑战。从规范 3.1 开始,必须实现一些新方法。

  • 已完成
  • 准备就绪
  • setReadListener

我正在寻找有关如何实现这些方法的示例或一些代码。有什么提示吗?

最佳答案

示例实现:

import com.google.common.primitives.Bytes;
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.io.InputStream;
import java.util.Arrays;

public class AuthenticationRequestWrapper extends HttpServletRequestWrapper {

// tag::variables[]
private byte[] requestBody = new byte[0];
private boolean bufferFilled = false;
// end::variables[]

/**
- Constructs a request object wrapping the given request.
*
- @param request The request to wrap
- @throws IllegalArgumentException if the request is null
*/
public AuthenticationRequestWrapper(HttpServletRequest request) {
super(request);
}


// tag::getRequestBody[]
public byte[] getRequestBody() throws IOException {
if (bufferFilled) {
return Arrays.copyOf(requestBody, requestBody.length);
}

InputStream inputStream = super.getInputStream();

byte[] buffer = new byte[102400]; // 100kb buffer

int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
requestBody = Bytes.concat(this.requestBody, Arrays.copyOfRange(buffer, 0, bytesRead)); // <1>
}

bufferFilled = true;

return requestBody;
}
// end::getRequestBody[]

// tag::getInputStream[]
@Override
public ServletInputStream getInputStream() throws IOException {
return new CustomServletInputStream(getRequestBody()); // <1>
}
// end::getInputStream[]

private static class CustomServletInputStream extends ServletInputStream {

private ByteArrayInputStream buffer;

public CustomServletInputStream(byte[] contents) {
this.buffer = new ByteArrayInputStream(contents);
}

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

@Override
public boolean isFinished() {
return buffer.available() == 0;
}

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

@Override
public void setReadListener(ReadListener listener) {
throw new RuntimeException("Not implemented");
}
}
}

关于java - HttpServletRequestWrapper,setReadListener/isFinished/isReady 的示例实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29208456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com