问题描述
我已经实现了用于拦截请求/响应的ContainerRequestFilter,ContainerResponseFilter。对于正常的请求/响应来说,这很好。
但是对于4xx错误,过滤器不会执行/触发。我尝试使用@PreMatching
过滤器,并将@Priority
设置为尽可能低的值,但仍然发现过滤器未执行。
我还必须能够捕获以下错误的请求/响应正文:
BAD_REQUEST(400,"Bad Request"),UNAUTHORIZED(401,"Unauthorized"),FORBIDDEN(403,"Forbidden"),NOT_FOUND(404,"Not Found"),NOT_ACCEPTABLE(406,"Not Acceptable"),CONFLICT(409,"Conflict"),GONE(410,"Gone"),PRECONDITION_Failed(412,"Precondition Failed"),UNSUPPORTED_MEDIA_TYPE(415,"Unsupported Media Type")
有没有办法在过滤器中实现这一目标?
@Provider
@PreMatching
@Priority(20)
public class LoggingFilter implements ContainerRequestFilter,ContainerResponseFilter,WriterInterceptor {
private static final Logger LOGGER = LoggerFactory.getLogger(LoggingFilterTrial.class);
@Override
public void filter(ContainerRequestContext reqContext) throws IOException {
logRequest(reqContext);
}
@Override
public void filter(ContainerRequestContext containerRequestContext,ContainerResponseContext containerResponseContext) throws IOException {
// aroundWriteto will not be called for empty body
if(containerResponseContext.getEntity() == null) {
logResponse(null,containerRequestContext);
}
}
@Override
public void aroundWriteto(WriterInterceptorContext context)
throws IOException,WebApplicationException {
logResponse(context,null);
}
private void logRequest(ContainerRequestContext reqContext)
throws IOException {
//body
byte[] requestBody = getRequestBody(reqContext);
}
private void logResponse(WriterInterceptorContext context,ContainerRequestContext reqContext)
throws IOException {
byte[] responseBody = new byte[0];
//we pass context as null for empty body
if (context != null) {
responseBody = getResponseBody(context);
}
}
private byte[] getRequestBody(ContainerRequestContext reqContext) throws IOException {
byte[] reqBytes = IoUtils.toByteArray(reqContext.getEntityStream());
InputStream in = new ByteArrayInputStream(reqBytes);
reqContext.setEntityStream(in);
return reqBytes;
}
private byte[] getResponseBody(WriterInterceptorContext context) throws IOException {
OutputStream originalStream = context.getoutputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
context.setoutputStream(baos);
try {
context.proceed();
} finally {
baos.writeto(originalStream);
baos.close();
context.setoutputStream(originalStream);
}
return baos.toByteArray();
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)