在 ExceptionMapper 中获取原始 URI

Get the original URI in ExceptionMapper

我在 JAX-RS 中使用 ExceptionMapper。

 public class MyException implements ExceptionMapper<ConstraintViolationException> {

    @Override
    public Response toResponse(ConstraintViolationException exception) {
        ...
    }
}

一切正常。但是,无论如何我可以获得 URL 或生成异常的 HTTP 请求的句柄吗?

谢谢

在class中使用@Context并用它来获取原始请求:

@Context
private HttpServletRequest request;
@Override
public Response toResponse(ConstraintViolationException exception) {
   String requestURI = request.getRequestURI();

注入UriInfo using @Context:

@Context
private UriInfo uriInfo;

然后使用getRequestUri()方法获取请求URI:

URI uri = uriInfo.getRequestUri();

参考this answer for other types that can be injected with @Context.