Intro to JAX-RS Custom Validation

In this example, I will show the usage of ValidatorAdapter in association with @ValidateRequest annotation. For sending the request from UI, I will use ajax. You can use form submission if needed in your project. In that case, you will need @FormParam annotation to capture request parameters.

Below if the screenshot of functionality what we are going to acheive in this tutorial.

JAX-RS + Ajax  Validation example
JAX-RS + Ajax Validation example

Lets build this example tutorial step by step.

Step 1) Create a eclipse web project using maven

C:LokeshSetupworkspaceRESTfulValidation>mvn archetype:generate -DgroupId=com.howtodoinjava 
-DartifactId=RESTfulValidation -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

mvn eclipse:eclipse -Dwtpversion=2.0

Step 2) Update runtime dependencies in pom.xml file

<!-- core library -->
<!-- JAXB provider -->

Step 3) Update web.xml with path mapping information

 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "" >

  <display-name>Archetype Created Web Application</display-name>
  <!-- Auto scan REST service -->

Step 4) Create RESTful API on which validation will be performed

This API can have @ValidateRequest annotation at following levels:

  • Method level : It will enable the validation on that particular method.
  • Class level : It will enable the validation on all methods inside that class.

I am using this annotation at class level.



import org.jboss.resteasy.spi.validation.ValidateRequest;

public class UserService {
	public Response addUser(@QueryParam("firstName") String firstName, @QueryParam("lastName") String lastName)
		System.out.println("User added !!");
		return Response.ok().build();

Note: If you have used @ValidateRequest annotation at class level, and you want to disable validation on some APIs, you can use @DoNotValidateRequest annotation.

Step 5) Create your custom validator which will implement ValidatorAdapter class

Implemetation of ValidatorAdapter are automatically scanned by RESTEasy on start-up of application and registerd in context.

package com.howtodoinjava.validator;

import java.lang.reflect.Method;

import org.jboss.resteasy.spi.BadRequestException;
import org.jboss.resteasy.spi.validation.ValidatorAdapter;

public class CommonValidator implements ValidatorAdapter {

	public void applyValidation(Object resource, Method invokedMethod, Object[] args) 
		/*ValidateRequest classLevelValidateRequest = FindAnnotation.findAnnotation(invokedMethod.getDeclaringClass()
														.getAnnotations(), ValidateRequest.class);
		ValidateRequest methodLevelValidateRequest = FindAnnotation.findAnnotation(invokedMethod.getAnnotations(), ValidateRequest.class);
		boolean applyValidation = (classLevelValidateRequest != null || methodLevelValidateRequest != null);*/
		if( invokedMethod.getName().equalsIgnoreCase("addUser"))
			if(args == null || args.length != 2)
				throw new BadRequestException("Fill all fields");
			if(((String) args[0]).isEmpty())
				throw new BadRequestException("Fill first name");
			else if(((String) args[1]).isEmpty())
				throw new BadRequestException("Fill last name");


Step 6) Modify index.jap file to interact with REST API

This jsp file will contain HTML form with two input boxes. These text boxes will accept the first name and last name of user. We are trying to enable ajax powered validation functionality on this form.

<script lang="javascript">
	var xmlhttp;
	function postRequest(url, cfunc) {
		if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		} else {// code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		xmlhttp.onreadystatechange = cfunc;"POST", url, true);
	function submitForm() {
				function() {
					if (xmlhttp.readyState == 4 && xmlhttp.status != 200) {
						document.getElementById("error").innerHTML = "<h2><span style='color:red'>Fill all fields !!</span></h2>";
	<h1>JAX-RS Custom Validation</h1>
	<div id="error"></div>
	<form onclick="submitForm()" method="post">
			First Name : <input type="text" name="firstName" id="firstName"/>
			LastName : <input type="text" name="lastName" id="lastName"/>
		<input type="button" value="Add User" />
	By :

Step 7) Test the application

As soon as you try to submit emtry or half filled form, you get the validation error as shown in screen shot at start of post. Also, in server log you can verify the error logged as:

SEVERE: Failed executing POST /rest/users
org.jboss.resteasy.spi.BadRequestException: Fill first name
	at com.howtodoinjava.validator.CommonValidator.applyValidation(
	at org.jboss.resteasy.core.MethodInjectorImpl.invoke(
	at org.jboss.resteasy.core.ResourceMethod.invokeOnTarget(
	at org.jboss.resteasy.core.ResourceMethod.invoke(
	at org.jboss.resteasy.core.ResourceMethod.invoke(
	at org.jboss.resteasy.core.SynchronousDispatcher.getResponse(
	at org.jboss.resteasy.core.SynchronousDispatcher.invoke(
	at org.jboss.resteasy.core.SynchronousDispatcher.invoke(
	at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(
	at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(
	at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(
	at javax.servlet.http.HttpServlet.service(
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(
	at org.apache.catalina.core.StandardWrapperValve.invoke(
	at org.apache.catalina.core.StandardContextValve.invoke(
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(
	at org.apache.catalina.core.StandardHostValve.invoke(
	at org.apache.catalina.valves.ErrorReportValve.invoke(
	at org.apache.catalina.valves.AccessLogValve.invoke(
	at org.apache.catalina.core.StandardEngineValve.invoke(
	at org.apache.catalina.connector.CoyoteAdapter.service(
	at org.apache.coyote.http11.AbstractHttp11Processor.process(
	at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(
	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$ Source)
	at Source)
Sourcecode Download

Happy Learning !!



Notify of
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode