Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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

Steps

  • Implement filter
  • Extracts query parameter from ContainerRequestContext
  • Performs the validation – aborts the request with an appropriate response status (and the error message)
@Provider
@QueryParamValidator
public class JAXRSReqFilter implements ContainerRequestFilter {

    @Override
    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")) {
            requestContext.abortWith(Response
                .status(Response.Status.BAD_REQUEST)
                .entity("Invalid Query Param " + queryParam)
                .build());
        }
    }
}


Enforce Filter

  • Use @NameBinding to decorate custom annotation
  • Use the custom annotation on the JAX-RS method
@NameBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface QueryParamValidator {
    
}


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


Further Reading

Cheers!

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
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 }}