Validating JAX-RS Query Parameters

DZone 's Guide to

Validating JAX-RS Query Parameters

This quick and simple guide will walk you through the steps to validate JAX-RS query parameters using filters, including their creation and enforcement.

· Java Zone ·
Free Resource

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

        if (!queryParam.equals("p")) {
                .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


java ee ,java ,validation ,jax-rs ,tutorial

Published at DZone with permission of Abhishek Gupta , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}