JAX-RS/Jersey needs an @Required annotation for parameters

I’ve been using Jersey as a JAX-RS implementation for a little while now, and one thing that it could benefit from is the addition of an @Required annotation for resource method parameters. Right now, when parameters are not provided by the client/request, they are simply set to null, creating the need for duplicated null-checking in resource methods. An @Required annotation would solve this issue and reduce code duplication.

This isn’t so much of an issue for @PathParam parameters, (since you won’t even get to the proper resource method without a matching URI) but it does affect @HeaderParam and @QueryParam (among others) since they aren’t needed for Jersey to determine which resource method to invoke. By that definition, they are implicitly optional. There should be a way to make them required.

The behaviour of such a required annotation might be as follows:

  • If the request does not have the parameter, then by default a Response with Status.BAD_REQUEST (HTTP 400) would be returned to the client.
  • Some way of customizing the HTTP response code and message should also be provided.

Right now, there’s not really an elegant way to make something like a @HeaderParam required. Here are some solutions I’ve tried.
Continued