我有一个servlet过滤器拦截请求并检查自定义"加密"头:
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);
}
}
}
当标题存在时,我应解密请求正文并加密响应正文。 否则,应保持请求/响应主体不变。
如何仅在需要时更改响应?
答案 0 :(得分:2)
您需要使用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?