gpt4 book ai didi

Java过滤器-根据请求有条件地更改响应主体

转载 作者:搜寻专家 更新时间:2023-11-01 03:17:52 25 4
gpt4 key购买 nike

我有一个 servlet 过滤器,它拦截请求并检查自定义“加密” header :

public class EncryptionFilter extends GenericFilterBean{

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain filterChain) {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
if (httpRequest.getHeader("EncryptedCommunication") != null){
decryptedRequest = /*decrypt request body and forward to next filter*/
encryptedResponse = /*encrypt request body and forward to next filter*/
filterChain.doFilter(decryptedRequest, encryptedResponse);
}
else { /* communication not encrypted */
filterChain.doFilter(request, response);
}
}
}

当 header 存在时,我应该解密请求正文并加密响应正文。否则,应保持请求/响应正文不变。

如何仅在需要时更改响应?

最佳答案

您需要使用一个 HttpServletResponseWrapper 示例是:

filterChain.doFilter(servletRequest,
new HttpServletResponseWrapper((HttpServletResponse) servletResponse) {
@Override
public void setHeader(String name, String value) {
if (!HTTPCacheHeader.ETAG.getName().equalsIgnoreCase(name)) {
super.setHeader(name, value);
}
}
});

参见 http://www.programcreek.com/java-api-examples/javax.servlet.http.HttpServletResponseWrapper

这是如何设置正文的示例:

public class ReadTwiceHttpServletRequestWrapper extends HttpServletRequestWrapper {

private ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

public ReadTwiceHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
try {
IOUtils.copy(request.getInputStream(), outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}

@Override
public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(new ByteArrayInputStream(outputStream.toByteArray())));
}

@Override
public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
return new ServletInputStream() {

@Override
public int readLine(byte[] b, int off, int len) throws IOException {
return inputStream.read(b, off, len);
}

@Override
public boolean isFinished() {
return inputStream.available() > 0;
}

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

@Override
public void setReadListener(ReadListener arg0) {
// TODO Auto-generated method stub
}

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

public void setBody(String body) {
outputStream = new ByteArrayOutputStream();
try {
outputStream.write(body.getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

public String getBody() {
return new String(outputStream.toByteArray());
}

参见 How to get the XML from POST request and modify it in Servlet Filter?

关于Java过滤器-根据请求有条件地更改响应主体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41998283/

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