HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / RESTEasy / RESTEasy Bean Validation using Hibernate Validator Provider

RESTEasy Bean Validation using Hibernate Validator Provider

The Bean Validation API (JSR-303) defines a meta-data model and API for bean validation based on annotations. The functionality is achieved through the resteasy-hibernatevalidator-provider component. In order to integrate, we need to add resteasy-hibernatevalidator-provider.jar and hibernate-validator.jar files to the classpath.

If you are using maven the, you need to add only below dependency. Change the version number of RESTEasy with yours.

<dependency>
   <groupId>org.jboss.resteasy</groupId>
   <artifactId>resteasy-hibernatevalidator-provider</artifactId>
   <version>2.3.1.GA</version>
</dependency>

Step 1) Add the validation specific annotations in API parameters

You can use various annotations for validating the request parameters and form input. For example, I have used @NotNull and @Size annotations. Read about all available annotations in link. No not forget to add @ValidateRequest annotation on method API. @ValidateRequest enables the validation on method where it is applied.

package com.howtodoinjava.rest;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;

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

@Path("/rest")
public class UserService 
{
	@Path("/users")
	@POST
	@ValidateRequest
	public Response addUser
	(
			@NotNull
			@Size(min=1,max=50) 
			@FormParam("firstName") String firstName  , 
			
			@Size(max=50)
			@FormParam("lastName") String lastName
	)
	{
		return Response.ok().entity("User "" + firstName + " " + lastName + "" added through JAX-RS JavaScript API").build();
	}
}

Step 2) Add validation exception handler

Well this is important step because hibernate validator plugin does not have any facility for exception handling, so you need to embed yous. Exception handlers in RESTEasy are used using the ExceptionMapper class.

package com.howtodoinjava.exception;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.hibernate.validator.method.MethodConstraintViolationException;

@Provider
public class ValidationExceptionHandler implements ExceptionMapper<MethodConstraintViolationException> 
{
	@Override
	public Response toResponse(MethodConstraintViolationException exception) 
	{
		return Response.status(Status.BAD_REQUEST).entity("Fill all fields").build();
	}
}

Step 3) Build the client code and test application

I have written a normal HTML form which will send two parameters for firstName and lastName parameters using form submission. Parameter validation is performed automatically and if validation failed, exception handler is invoked to return correct status code.

<html>
	<body>
		<h1>RESTEasy Hibernate Validator Plugin</h1>
		<div id="error"></div>
		<form method="post" action="./rest/users">
			<p>First Name : <input type="text" name="firstName" id="firstName"/></p>
			<p>LastName : <input type="text" name="lastName" id="lastName"/></p>
			<input type="submit" value="Add User" />
		</form>
		Demo by : <b>//howtodoinjava.com</b>
	</body>
</html>

You can test the above application either in browser window or you can use some REST testing tools like RESTClient firefox plugin.

RESTEasy bean validation using hibernate validator
RESTEasy bean validation using hibernate validator

To Download the sourcecode of this demo, follow below link.

Sourcecode Download

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.

Share this:

  • Twitter
  • Facebook
  • LinkedIn
  • Reddit

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. NotionQuest

    May 12, 2017

    @ValidateRequest is not available on resteasy-jaxrs-3.1.2.Final. Do you have any working examples using 3.x?

  2. Abdulla

    April 22, 2015

    Can you please provide java config equivalent of web.xml file

  3. Frank Ruenagel

    August 29, 2013

    Thank you for your very helpful post. But MethodConstraintViolationException is deprecated in Hibernate Validator 4.3.1 and does not exist any more in 5.

Comments are closed on this article!

Search Tutorials

RESTEasy Tutorial

  • JAX-RS – Introduction
  • RESTEasy – JBoss
  • RESTEasy – Tomcat
  • RESTEasy – @Path
  • RESTEasy – HATEOAS
  • RESTEasy – SLF4J
  • RESTEasy – Log4j
  • RESTEasy – Download
  • RESTEasy – Upload (MultipartForm)
  • RESTEasy – Upload (HTTPClient)
  • RESTEasy – Custom Validation
  • RESTEasy – Hibernate Validator
  • RESTEasy – ContainerRequestFilter
  • RESTEasy – PreProcessorInterceptor
  • RESTEasy – JAXB XML
  • RESTEasy – Jettison JSON
  • RESTEasy – Jackson JSON
  • RESTEasy – ExceptionMapper

RESTEasy Client APIs

  • RESTEasy – java.net
  • RESTEasy – JAX-RS Client
  • RESTEasy – Apache HttpClient
  • RESTEasy – JavaScript API
  • RESTEasy – ResteasyClientBuilder

RESTEasy Best Practices

  • RESTEasy – Sharing Context Data
  • RESTEasy – Exception Handling
  • RESTEasy – ETag Cache control
  • RESTEasy – GZIP Compression
  • RESTful vs. SOAP

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Java 15 New Features
  • Sealed Classes and Interfaces
  • EdDSA (Ed25519 / Ed448)