0

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;
    }
}
Thijs0001
  • 3
  • 1

2 Answers2

1

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")
}
Attila T
  • 577
  • 1
  • 4
  • 18
0

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