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

Time:10-20

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;
    }
}

CodePudding user response:

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 ;

 return new ResponseEntity<>(DatabaseAccess.getAlerts(), HttpStatus.OK);

        }
        return ResponseEntity.badRequest().body("Bad request")
    }
  • Related