Jersey 2.22.2 官方文档第7章学习笔记

来源:互联网 发布:ipad版怎么看淘宝直播 编辑:程序博客网 时间:2024/05/29 10:19

官网文档地址:https://jersey.java.net/documentation/latest/representations.html#d0e6665

第7章

7.2 创建Responses对象

有时,对于一个Request请求,需要返回额外的信息。这些信息能够通过使用Response对象与ResponseBuilder对象来创建并返回。例如,Restful新资源的创建是通过一个POST请求并返回201(状态码)以及响应头的形式来完成。其URI是新创建的资源。上述过程可以通过下面的代码来实现。

@Path("buildResp")public class BuildingResponse {@GET@Consumes(MediaType.TEXT_PLAIN)public Response post(@QueryParam("content")String content){URI createUri = URI.create("xxx.ll.com/ss");return Response.created(createUri).build();}}

发出请求 http://localhost:9998/buildResp?content=1234   返回结果如下图所示。

但上面的代码没有任何返回数据,返回数据可以通过ResponseBuilder的entity方法来添加。

@Path("buildResp")public class BuildingResponse {          @GET          @Consumes(MediaType.TEXT_PLAIN)          public Response post(@QueryParam("content")String content){                    URI createUri = URI.create("xxx.ll.com/ss");                    return Response.created(createUri).entity(content).build();          }}

除了entity还可以设置其它的属性,如last modified等。

7.3 WebApplicationException 异常与异常转换为并通过Response返回

7.2节演示了如何返回Http response对象。当在try-catch中处理异常时,可以通过同样的方法返回HTTP 错误。为了与Java编程模型保持一致,JAX-RS允许建立Java异常与Http error response对象的映射关系。下面的代码演示了从resource方法中抛出CustomNotFoundException异常,并以Http response来返回给客户端。

@Path("buildResp")public class BuildingResponse {           @GET          @Consumes(MediaType.TEXT_PLAIN)          public Response post(@QueryParam("content") String content) {                    if (content.equals("1")) {                              throw new CustomNotFoundException("{msg:content null exception,code:100001}");                    }                    URI createUri = URI.create("xxx.ll.com/ss");                    return Response.created(createUri).entity(content).build();          }}public class CustomNotFoundException extends WebApplicationException {           private static final long serialVersionUID = -5532594936351897109L;           public CustomNotFoundException() {                    super(Response.status(404).build());          }           public CustomNotFoundException(String message) {                    super(Response.status(404).entity(message).type(MediaType.APPLICATION_JSON).build());          }}

发出请求 http://localhost:9998/buildResp


除了通过WebApplicationException映射异常,还可以通过实现 ExceptionMapper<E extends Throwable>接口来映射异常。

@Path("buildResp")public class BuildingResponse {           @GET          @Consumes(MediaType.TEXT_PLAIN)          public Response post(@QueryParam("content") String content) {                    if (content.equals("1")) {                              throw new RuntimeException("{msg:content null exception,code:100001}");                    }                    URI createUri = URI.create("xxx.ll.com/ss");                    return Response.created(createUri).entity(content).build();          }}@Providerpublic class EntityNotFoundMapper implements ExceptionMapper<Exception>{           public Response toResponse(Exception exception) {                    // TODO Auto-generated method stub                    return Response.status(404).entity(exception.getMessage()).type("text/plain")                                        .build();          }}


上面的代码带有@Provider注解。当系统抛出Exception异常,EntityNotFoundMapper的toResponse方法将被调用。Jersey支持异常映射器的扩展。扩展的异常映射器必须实现org.glassfish.jersey.spi.ExtendedExceptionMapper接口。这个接口继承与前面所提到的ExceptionMapper<T>接口,并提供了isMappable(Throwable)方法。该方法判断所提供的异常是否能被处理。当返回true时,表示能够处理,false表示不能处理。在运行时,当异常被抛出,该方法将被调用。因此创建ExtendedExceptionMapper子类,然后实现isMappable方法,有选择地对异常处理。

@Providerpublic class ExtendExceptionMapper implements ExtendedExceptionMapper<Exception>{           public Response toResponse(Exception exception) {                    return Response.status(404).entity("{status:failed,code:1002}").build();          }           public boolean isMappable(Exception exception) {                    // TODO Auto-generated method stub                    if(exception instanceof NullPointerException){                              return false;                    }                    return true;          } }@Path("buildResp")public class BuildingResponse {           @GET          @Consumes(MediaType.TEXT_PLAIN)          public Response post(@QueryParam("content") String content) {                    if (content.equals("1")) {                              throw new RuntimeException("{msg:content null exception,code:100001}");                    }                    URI createUri = URI.create("xxx.ll.com/ss");                    return Response.created(createUri).entity(content).build();          }}
发起请求http://localhost:9998/buildResp?content=1

修改isMappble方法后,异常被没有被映射处理。因此返回500,而不是返回定义的http响应码。

public boolean isMappable(Exception 
    if(exception instanceof NullPointerException){             return true;    }    return false;}


因此当我们需要对某且异常映射处理进行拦截,并进行选择性处理时,实现ExtendedExceptionMapper接口即可。

0 0