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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@NameBinding | |
@Retention(RetentionPolicy.RUNTIME) | |
@Target({ElementType.TYPE, ElementType.METHOD}) | |
public @interface QueryParamValidator { | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Path("test") | |
public class TestResource { | |
@GET | |
@QueryParamValidator | |
public String test(@QueryParam("p") String p){ | |
return "Param "+ p + " on " + new Date(); | |
} | |
} |
Further reading
- My eBook: REST assured with JAX-RS
- JAX-RS 2.0 article in the Java Magazine
Cheers!