如何解决未在JAX-RS中执行的针对4xx错误的过滤器
我已经实现了用于拦截请求/响应的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 举报,一经查实,本站将立刻删除。