Jonathan Vukadinovic
Jonathan Vukadinovic

Reputation: 264

One request to servlet that can have two types of response

I have a thread running on my server (I'm using Tomcat and Java files) and when a user makes a request the server can respond with two types of responses depending on the state of the thread. The responses should be in JSON and I'm using the Jersey library and the Servlet looks something like:

@GET
@Path("init")
@Produces(MediaType.APPLICATION_JSON)
public initResponse respondAsReady() {
    return initRes;
}

this is just an example but the problem is I am limited to using one type of JSON response (in this case initResponse) but I need to be able to return another type of response (say initResponse2) which is a different type of JSON. And in other cases I need to respond with either just an integer or with a JSON object. So how can I structure my backend so that it can handle requests and return two possible responses?

Upvotes: 0

Views: 841

Answers (2)

Naili
Naili

Reputation: 1602

@GET
@Path("init")
@Produces({MediaType.APPLICATION_JSON , MediaType.TEXT_PLAIN})
public Response respondAsReady() {
    if(/*condition*/)}
        //In case of a JSON response
        return Response.ok(json, MediaType.APPLICATION_JSON).build();
    }
    if(/*condition*/){
        //In case of an integer response
        return Response.ok(text, MediaType.TEXT_PLAIN).build();
    }
}

Upvotes: 2

Koitoer
Koitoer

Reputation: 19533

Each endpoint that you have should have @Consumes annotation, this annotation defines the media types that the methods of a resource class or MessageBodyReader can accept, also you need to use @Produces this defines the media type(s) that the methods of a resource class or MessageBodyWriter can produce

@GET
@Path("init")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public InitResponse respondAsReady() {
    return new InitResponse;
}

@GET
@Path("init")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String respondAsReady() {
    return new String("5");
}

Using this jersey select the method based on the Accept header in the request, so be sure to send it with your request. Read this link to learn more about it

If your client accept only 'text/plain' the second endpoint will be executed. Just past this value in the Accept header.

Upvotes: 1

Related Questions