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

本文介绍如何使用JAX-RS创建HTTP响应及处理异常。包括通过ResponseBuilder构建响应对象并返回特定状态码的方法,以及如何通过自定义异常和实现ExceptionMapper接口来处理并映射异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官网文档地址: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();
          }
}
@Provider
public 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方法,有选择地对异常处理。

@Provider
public 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接口即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值