我有一个Spring应用程序,之后还有一个过滤器。
我的代码是:
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (response.getCharacterEncoding() == null) {
response.setCharacterEncoding(StandardCharsets.UTF_8.toString());
}
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
try {
allowAccess = checkEncryption(httpServletRequest, httpServletResponse); // it returns a boolean Value
if (allowAccess) {
String bodyContent =
Utils.parseInputStreamToString(httpServletRequest.getInputStream());
String body = decryptMessage(bodyContent); // decrypt the message using some algorithm
HttpServletRequestWritableWrapper httpServletRequestWritableWrapper =
new HttpServletRequestWritableWrapper(httpServletRequest,
body.getBytes());
HttpServletResponseReadableWrapper responseWrapper =
new HttpServletResponseReadableWrapper(httpServletResponse);
httpServletRequestWritableWrapper.addHeader(HEADER_TRANSACTION_ID,
Long.toString(System.currentTimeMillis()) + UUID.randomUUID().toString());
chain.doFilter(httpServletRequestWritableWrapper, responseWrapper);
String encryptedResponse = encryptResponseContent(
new String(Hex.encode(responseWrapper.getResponseBody())), publicServerKey);
LOGGER.info("Encrypted Response = " + encryptedResponse + "\n commites:"
+ httpServletResponse.isCommitted() + ", " + responseWrapper.isCommitted());
if (!httpServletResponse.isCommitted()) {
httpServletResponse.setContentType(MediaType.TEXT_PLAIN_VALUE);
httpServletResponse.resetBuffer();
httpServletResponse.getOutputStream().write(encryptedResponse.getBytes());
httpServletResponse.getOutputStream().close();
}
} else {
LOGGER.info("Invalid Access!!");
if (!httpServletResponse.isCommitted())
httpServletResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED,
ERROR_MESSAGE_INVALID_PERMISSION);
}
} catch (Excetion e) {
LOGGER.info(""+e);
}
}
我有一个错误请求的请求,该请求返回了401未经授权的请求,但是如果我用正确的请求更改了请求,并且调用了过滤器,则在第一次调用后总是有httpServletResponse.isCommitted() = true
。
每次根据请求我都需要发送正确的响应(如果更改请求,为什么会出现commit = true),该如何解决?
非常感谢。