Validate JAX-RS query parameters


It’s easy to validate parameters in JAX-RS using filters – ContainerRequestFilter to be specific. There are other options at your disposal e.g. using (CDI or EJB) interceptors, or injecting (HttpServletRequest using @Context)

Scenario – Validate query parameter passed in by the caller


  • Implement filter
  • Extracts query parameter from ContainerRequestContext
  • Performs the validation – aborts the request with an appropriate response status (and the error message)

public class JAXRSReqFilter implements ContainerRequestFilter{
public void filter(ContainerRequestContext requestContext) throws IOException {
MultivaluedMap<String, String> queryParameters = requestContext.getUriInfo().getQueryParameters();
String queryParam = queryParameters.keySet().stream().findFirst().get();
System.out.println("Query param – "+ queryParam);
.entity("Invalid Query Param "+ queryParam)

Enforce filter

  • Use @NameBinding to decorate custom annotation
  • Use the custom annotation on the JAX-RS method

@Target({ElementType.TYPE, ElementType.METHOD})
public @interface QueryParamValidator {

public class TestResource {
public String test(@QueryParam("p") String p){
return "Param "+ p + " on " + new Date();

Further reading





About Abhishek

Loves Go, NoSQL DBs and messaging systems
This entry was posted in Java, Java EE and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s