Thijs0001
Thijs0001

Reputation: 3

TomCat how to send an HTTP status code instead of the normal JSON response?

I'm building a webserver in TomCat, and trying to implement a function that returns a list normally, but I want it to first check if the user has a valid session. If the user does not have a valid session I want to send back a response with http status code 403. How can I do this? I can only return an empty list. This is my current code:

public class AlertsResource {
    @Context
    UriInfo uriInfo;
    @Context
    Request request;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Alert> getAlerts(@HeaderParam("sessionId") String sessionId) {
        if (isValid(sessionId)) {
            return DatabaseAccess.getAlerts();
        }
        return null;
    }
}

Upvotes: 0

Views: 361

Answers (2)

ANISH SAJI  KUMAR
ANISH SAJI KUMAR

Reputation: 130

If you want to send an HTTP status code instead of the normal JSON response, you can use the response.sendStatus() method.

Upvotes: 0

Selvam Ramasamy
Selvam Ramasamy

Reputation: 26

You can use ResponseEntity with a status code:

@GET
@Produces(MediaType.APPLICATION_JSON)
public ResponseEntity<List<Alert>> getAlerts(@HeaderParam("sessionId") String sessionId) {
    if (isValid(sessionId)) {
        return new ResponseEntity<>(DatabaseAccess.getAlerts(), HttpStatus.OK);
    }
    return ResponseEntity.badRequest().body("Bad request")
}

Upvotes: 1

Related Questions