gpt4 book ai didi

rest - 在 JAX RS 中,返回 Response 和 Bean 或 Collection of Beans (DTO) 之间的区别

转载 作者:行者123 更新时间:2023-12-04 21:08:05 24 4
gpt4 key购买 nike

我正在构建一个 REST api。我的问题是,在使用 Jersey 时,我的服务构建和返回 Response 对象或返回 bean 或集合之间有什么区别。我只关心成功的调用,我正在为错误和异常情况抛出适当的异常。

下面是一个例子:

@Produces(MediaType.APPLICATION_JSON)
public Response search(FooBean foo){
List<FooBean> results = bar.search(foo);
return Response.ok(results).build();
}

对比
@Produces(MediaType.APPLICATION_JSON)
public List<FooBean> search(FooBean foo){
List<FooBean> results = bar.search(foo);
return results;
}

我已经看到使用了两个示例,我更喜欢第二种情况,只是为了更容易识别服务方法。我已经检查了对这两种方法的 react ,它们似乎是相同的。

想法?

最佳答案

JAX-RS 规范中解释了这些差异:

3.3.3 Return Type

Resource methods MAY return void, Response, GenericEntity, or another Java type, these return types are mapped to a response entity body as follows:

void
Results in an empty entity body with a 204 status code.

Response
Results in an entity body mapped from the entity property of the Response with the status code specified by the status property of the Response. A null return value results in a 204 status code. If the status property of the Response is not set: a 200 status code is used for a non-null entity property and a 204 status code is used if the entity property is null.

GenericEntity
Results in an entity body mapped from the Entity property of the GenericEntity. If the return value is not null a 200 status code is used, a null return value results in a 204 status code.

Other
Results in an entity body mapped from the class of the returned instance. If the return value is not null a 200 status code is used, a null return value results in a 204 status code.

Methods that need to provide additional metadata with a response should return an instance of Response, the ResponseBuilder class provides a convenient way to create a Response instance using a builder pattern.



“常规”bean 的映射方式与 Response 几乎相同是,除了 Response允许您设置其他元数据(响应 header 、专用状态、专用内容类型等)。至于使用哪个,那完全取决于你自己决定 - Response为您提供更大的灵活性,但常规 bean 更“自我记录”。

关于rest - 在 JAX RS 中,返回 Response 和 Bean 或 Collection of Beans (DTO) 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16303544/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com