如何从JAX-RS获取原始请求的URI javax.ws.rs.core.Response
问题描述:
我正在尝试为JAX-RS编写一个定制的ExceptionMapper
类。我想以某种方式读取来自JAX-RS javax.ws.rs.core.Response
对象的原始请求URI。如何从JAX-RS获取原始请求的URI javax.ws.rs.core.Response
当我检查与在调试模式下的IntelliJ IDEA响应对象然后我可以看到下面的路径下此信息:响应>上下文> resolvedUri其中
类型context
的是org.glassfish.jersy.client.ClientResponse
。这个类有一个resolvedUri
变量,它拥有我需要的信息。
我能以某种方式获得这些信息吗?我如何写我的getRequestUri(response)
方法?
public class MyExceptionMapper implements ExceptionMapper<WebApplicationException> {
@Override
public Response toResponse(WebApplicationException error) {
Response response = error.getResponse();
ErrorResponse errorResponse = ErrorResponseBuilder
.builder()
.httpStatus(getDefaultStatusCodeIfNull(response))
.errorMessage(getCustomErrorMessage(response))
.requestedUri(getRequestedUri(response)) <--------- HOW TO READ IT?
.build();
return Response
.status(errorResponse.getHttpStatus())
.type(ExtendedMediaType.APPLICATION_JSON)
.entity(errorResponse)
.build();
}
}
答
使用
@Context 私人的HttpServletRequest的servletRequest;
并使用HttpServletRequest.getRequestURI()
public class MyExceptionMapper implements
ExceptionMapper<WebApplicationException> {
@Context
private HttpServletRequest servletRequest;
@Override
public Response toResponse(WebApplicationException error) {
Response response = error.getResponse();
ErrorResponse errorResponse = ErrorResponseBuilder
.builder()
.httpStatus(getDefaultStatusCodeIfNull(response))
.errorMessage(getCustomErrorMessage(response))
.requestedUri(servletRequest.getRequestURI())
.build();
return Response
.status(errorResponse.getHttpStatus())
.type(ExtendedMediaType.APPLICATION_JSON)
.entity(errorResponse)
.build();
}
}
你试过'URI URI = response.getLocation(); System.out.println(uri.toString());'? – Anddo
我试过了。它返回null :( – zappee
不确定,但作为Java [API文档](http://docs.oracle.com/javaee/7/api/javax/ws/rs/core/Response.html#getLocation--)它如果**不存在,则返回位置URI,否则返回null – Anddo