【问题标题】:How to return Response with message, jax rs如何返回带有消息的响应,jax rs
【发布时间】:2018-02-22 07:14:13
【问题描述】:

我有一个使用 jax-rs 的 Web 服务休息,我的服务返回一个对象列表,但你不知道如何将自定义状态值添加到响应中,例如 我要构建的结果如下:

如果没问题:

{
   "status": "success",
   "message": "list ok!!",
   "clients": [{
        "name": "john",
        "age": 23
    },
    {
        "name": "john",
        "age": 23
    }]
}

如果是错误:

{
   "status": "error",
   "message": "not found records",
   "clients": []
}

我的休息服务:

 @POST
 @Path("/getById")
 @Consumes(MediaType.APPLICATION_JSON)
 @Produces(MediaType.APPLICATION_JSON)
 public List<Client> getById(Client id) {

  try {

       return Response.Ok(new ClientLogic().getById(id)).build();
       //how to add status = success, and message = list! ?

    } catch (Exception ex) {
       return  ??   
       // ex.getMessage() = "not found records"
       //i want return json with satus = error and message from exception
    }
    } 

【问题讨论】:

    标签: java json return jax-rs response


    【解决方案1】:

    我遇到了同样的问题,这就是我解决它的方法。 如果您的服务方法成功,则返回 Response 状态为 200 和您想要的实体。如果您的服务方法抛出异常,则返回具有不同状态的 Response 并将异常消息绑定到您的 RestError 类。

    @POST
    @Path("/getById")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response getById(Client id) {
      try {    
        return Response.Ok(new ClientLogic().getById(id)).build();
      } catch (Exception ex) {
        return Response.status(201) // 200 means OK, I want something different
                       .entity(new RestError(status, msg))
                       .build();   
      }
    }
    

    在客户端,我使用这些实用方法从响应中读取实体。如果有错误,我会抛出一个异常,其中包含该错误的状态和消息。

    public class ResponseUtils {
    
      public static <T> T convertToEntity(Response response, 
                                          Class<T> target)
                              throws RestResponseException {
        if (response.getStatus() == 200) {
          return response.readEntity(target);
        } else {
          RestError err = response.readEntity(RestError.class);
          // my exception class
          throw new RestResponseException(err);
        }
      }
    
      // this method is for reading Set<> and List<> from Response
      public static <T> T convertToGenericType(Response response,
                                               GenericType<T> target)
                              throws RestResponseException {
        if (response.getStatus() == 200) {
          return response.readEntity(target);
        } else {
          RestDTOError err = response.readEntity(RestError.class);
          // my exception class
          throw new RestResponseException(err);
        }
      }
    
    }
    

    我的客户端方法将调用(通过代理对象)服务方法

    public List<Client> getById(Client id) 
                            throws RestResponseException {
      return ResponseUtils.convertToGenericType(getProxy().getById(id),
                                                new GenericType<List<Client>>() {});
    } 
    

    【讨论】:

      【解决方案2】:

      如果您想完全控制您的输出 JSON 结构,请使用 JsonObjectBuilder(如 here 所述,然后将您的最终 json 转换为 String 并写入(例如成功的 json):

      return Response.Ok(jsonString,MediaType.APPLICATION_JSON).build();
      

      并将您的返回值更改为 Response 对象。

      但是请注意,您正在尝试发送冗余(而非标准)信息,该信息已编码到 HTTP 错误代码中。当您使用 Response.Ok 时,响应将包含代码“200 OK”,您可以研究 Response 类方法来返回您想要的任何 HTTP 代码。 在您的情况下,它将是:

      return Response.status(Response.Status.NOT_FOUND).entity(ex.getMessage()).build();
      

      返回一个 404 HTTP 代码(查看Response.Status 代码列表)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-02-06
        • 1970-01-01
        • 2014-10-19
        • 1970-01-01
        • 2017-01-11
        • 2023-03-14
        • 2013-06-09
        • 1970-01-01
        相关资源
        最近更新 更多