In JAX RS, differences between returning Response and Bean or Collection of Beans (DTO)

前端 未结 3 1270
终归单人心
终归单人心 2021-01-30 04:08

I am working on building a REST api. My question is, when using Jersey, what are the differences between my services building and returning a Response object or returning the th

3条回答
  •  半阙折子戏
    2021-01-30 04:30

    There is no diference if you want to return always the response 200 - OK , catching and manipulate all the exceptions that may occur before of after your method return the result, with interceptions or WebApplicationException. So, both of these methods will result the same responses.

    The only diference is at specific scenarios, like returning null objects, or creating object, like this example:

    @POST
    @Consumes("application/json")
    public Response post(String content) {
        URI createdUri = ...
        Object createdContent = create(content);
        return Response.created(createdUri).entity(createdContent).build();
    }
    

    In this case the return will be 201 - CREATED (With the URI to access the created object)

    So, the following method:

    @POST
    @Consumes("application/json")
    public Object post(String content) {
        URI createdUri = ...
        Object createdContent = create(content);
        return createdContent;
    }
    

    ... will return a response 200 - OK

    If you don't care about which response status your client will receive, you can use any of declarations without problem.

    Source: Jersey.

提交回复
热议问题