hibernate

Hibernate validator example

Photo of Theodora FragkouliTheodora FragkouliSeptember 15th, 2014Last Updated: February 21st, 2019
1 455 6 minutes read

This is an example of how to make use ofHibernate validator API.Hibernate validator can be used to validate data, which is a very important issue in every layer of an application. For example, validating is important when submitting HTML forms.Hibernate validator framework provides many annotations, that can be used to validate input fields of a form against constraints.

In order to check howhibernate validator works, we will make use ofSpring-MVC to create a simple form page. Each field in the form has a validation constraint set by the annotations provided by theHidernate validator package.
 
 
 

Tip
You may skip project creation and jump directly to thebeginning of the example below.

Our preferred development environment isEclipse. We are using Eclipse Juno (4.2) version, along withMaven Integration plugin version 3.1.0. You can download Eclipse fromhere and Maven Plugin for Eclipse fromhere. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using JDK 7_u_21.Hibernate-validator 5.1.0 Final andSpring MVC are inserted as dependencies thruoughMaven andTomcat 7 is the application server.

Let’s begin,

1. Create a new Maven project

Go to File -> Project ->Maven -> Maven Project.

New Maven Project
New Maven Project – step 1

In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option isunchecked, hit “Next” to continue with default values.

New Maven project
New Maven project- step 2

Here the maven archetype for creating a web application must be added. Click on“Add Archetype” and add the archetype. Set the “Archetype Group Id” variable to"org.apache.maven.archetypes", the “Archetype artifact Id” variable to"maven-archetype-webapp" and the “Archetype Version” to"1.0". Click on“OK” to continue.

maven-archetype-webapp
Add Maven archetype

In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. Set the “Group Id” variable to"com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to"springexample". The aforementioned selections compose the main project package as"com.javacodegeeks.snippets.enterprise.springexample" and the project name as"springexample". Set the “Package” variable to"war", so that a war file will be created to be deployed to tomcat server. Hit “Finish” to exit the wizard and to create your project.

Configure Maven project
Configure Maven project

The Maven project structure is shown below:

New project structure
New project structure

    It consists of the following folders:

  • /src/main/java folder, that contains source files for the dynamic content of the application,
  • /src/test/java folder contains all source files for unit tests,
  • /src/main/resources folder contains configurations files,
  • /target folder contains the compiled and packaged deliverables,
  • /src/main/resources/webapp/WEB-INF folder contains the deployment descriptors for the Web application ,
  • the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.

2. Add dependencies

Add the dependencies in Maven’spom.xml file, by editing it at the “Pom.xml” page of the POM editor. The dependencies needed arespring-webmvc package, thejavax.validation and thehibernate-validator packages:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.javacodegeeks.snippets.enterprise</groupId><artifactId>springexample</artifactId><packaging>war</packaging><version>0.0.1-SNAPSHOT</version><name>springexample Maven Webapp</name><url>http://maven.apache.org</url><dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring.version}</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version></dependency><dependency>            <groupId>javax.validation</groupId>            <artifactId>validation-api</artifactId>            <version>1.1.0.Final</version>        </dependency>        <dependency>            <groupId>org.hibernate</groupId>            <artifactId>hibernate-validator</artifactId>            <version>5.1.0.Final</version>        </dependency></dependencies><build><finalName>springexample</finalName></build><properties><spring.version>3.2.9.RELEASE</spring.version></properties></project>

3. Create the model with the validation annotations

TheForm.java class is a simple class with fields, that will be used as the MVC model. All the fields have annotations, so when the form is submitted all fields will be validated. The validation annotations used are the ones below:

  • @Size : This annotation is used to set the size of the field. It has three properties to configure, themin,max and themessage to be set.
  • @Min : This annotation is used to set the min size of a field
  • @NotNull : With this annotation you can make sure that the field has a value.
  • @Length : This annotation is similar to@Size.
  • @Pattern : This annotation can be used when we want to chack a field against a regular expression. Theregex is set as an attribute to the annotation.
  • @Range : This annotation can be used to set a range of min and max values to a field.

Form.java

package com.javacodegeeks.snippets.enterprise.form.model;import javax.validation.constraints.Min;import javax.validation.constraints.NotNull;import javax.validation.constraints.Pattern;import javax.validation.constraints.Size;import org.hibernate.validator.constraints.Length;import org.hibernate.validator.constraints.Range;public class Form {@Size(min=5, max=10, message="Your name should be between 5 - 10 characters.")private String name;@Min(value=5, message="Please insert at least 5 characters")private String lastname;@NotNull(message="Please select a password")@Length(min=5, max=10, message="Password should be between 5 - 10 charactes")private String password;@Pattern(regexp="[0-9]+", message="Wrong zip!")private String zip;@Pattern(regexp=".+@.+\\..+", message="Wrong email!")private String email;@Range(min=18, message="You cannot subscribe if you are under 18 years old.")private String age;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getLastname() {return lastname;}public void setLastname(String lastname) {this.lastname = lastname;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public String getZip() {return zip;}public void setZip(String zip) {this.zip = zip;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getAge() {return age;}public void setAge(String age) {this.age = age;}}

4. Create a controller

TheController is where theDispatcherServlet will delegate requests. The@Controller annotation indicates that the class serves the role of a Controller. The@RequestMapping annotation is used to map a URL to either an entire class or a particular handler method.

Want to be a Hibernate Master ?
Subscribe to our newsletter and download the HibernateUltimateGuideright now!
In order to help you master JPA and database programming with Hibernate, we have compiled a kick-ass guide with all the major Hibernate features and use cases! Besides studying them online you may download the eBook in PDF format!

Thank you!

We will contact you soon.

The Controller consists of two basic methods, a GET method, which isString initForm(Model model) and a POST method, which isString submitForm(Model model, @Valid Form form, BindingResult result). The first method creates and returns to the"form" view a new instance of theForm.java class. The second method gets theForm object created in the form.Form is annotated with the@Valid annotation, which allows the form object to be validated with the validation annotations set in theForm.java class.BindingResult is where all validation errors are automatically passed, so it can be used to decide the next navigation step. If there are no errors, the validation is successful, so the method returns the String representation of thesuccessForm.jsp page, and the form object is passed at theModel. Otherwise, the returned String is the String representation of theform.jsp page, which also has the error messages, as will be shown below.

FormController.java

package com.javacodegeeks.snippets.enterprise.form;import javax.validation.Valid;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.validation.BindingResult;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.javacodegeeks.snippets.enterprise.form.model.Form;@Controller@RequestMapping("/form.htm")public class FormController {@RequestMapping(method = RequestMethod.GET)public String initForm(Model model) {Form form = new Form();model.addAttribute("form", form);return "form";}@RequestMapping(method = RequestMethod.POST)public String submitForm(@Valid Form form, BindingResult result) {String returnVal = "successForm";if(result.hasErrors()) {returnVal = "form";}return returnVal;}}

5. Create a view

We make use of theform:form tag. Itsmethod property is set to POST, and thecommandName property is set to the name of the backing bean that is binded to the Model, which is theForm.java class.

Theform:input tag is used to create all the input fields, with itspath property set to every field binded to it. Theform:errors tag defines where the error message of the specified field will be displayed in the view. Finally, theinput tag, withtype property set tosubmit is used for the submit button.

form.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%><html><head><title>Spring MVC form submission</title></head><body><h2>Fill your form!</h2><form:form method="POST" commandName="form"><table><tr><td>Enter your name:</td><td><form:input path="name" /></td><td><form:errors path="name" cssStyle="color: #ff0000;"/></td></tr><tr><td>Enter your lastname:</td><td><form:input path="lastname" /></td><td><form:errors path="lastname" cssStyle="color: #ff0000;" /></td></tr><tr><td>Enter your password:</td><td><form:input path="password" /></td><td><form:errors path="password" cssStyle="color: #ff0000;" /></td></tr><tr><td>Enter your zip:</td><td><form:input path="zip" /></td><td><form:errors path="zip" cssStyle="color: #ff0000;" /></td></tr><tr><td>Enter your email:</td><td><form:input path="email" /></td><td><form:errors path="email" cssStyle="color: #ff0000;" /></td></tr><tr><td>Enter your age:</td><td><form:input path="age" /></td><td><form:errors path="age" cssStyle="color: #ff0000;" /></td></tr><tr><td><input type="submit" name="submit" value="Submit"></td></tr><tr></table></form:form></body></html>

When validation succeeds, the page below will be rendered:

successForm.jsp

<html><head><title>Spring MVC form submission</title></head><body>Form successfully submitted.</body></html>

6. Configure the application

The files that we must configure in the application are theweb.xml file and themvc-dispatcher-servlet.xml file. You can check how to configure these files in detailhere.

7. Run the application

Now, let’s run the application. We first build the project with Maven and place the.war file produced inwebapps folder of tomcat. Then, we can start the server.

Hit on:

http://localhost:8080/springexample/form.htm

Press the submit button before having entered any values:

form validation
failed validation

As a result all validation messages are rendered. Now complete your form correctly and press on submit button:

successful validation
successful validation

The form is submitted sucessfully.

8. Download the Eclipse Project

This was an example of how to use Hibernate for validation.

Download
You can download the full source code of this example here:HibernateValidatorExample
Do you want to know how to develop your skillset to become aJava Rockstar?
Subscribe to our newsletter to start Rockingright now!
To get you started we give you our best selling eBooks forFREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to theTerms andPrivacy Policy

Thank you!

We will contact you soon.

Photo of Theodora FragkouliTheodora FragkouliSeptember 15th, 2014Last Updated: February 21st, 2019
1 455 6 minutes read
Photo of Theodora Fragkouli

Theodora Fragkouli

Theodora has graduated from Computer Engineering and Informatics Department in the University of Patras. She also holds a Master degree in Economics from the National and Technical University of Athens. During her studies she has been involved with a large number of projects ranging from programming and software engineering to telecommunications, hardware design and analysis. She works as a junior Software Engineer in the telecommunications sector where she is mainly involved with projects based on Java and Big Data technologies.

Related Articles

Subscribe
Notify of
guest
I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

I agree to theTerms andPrivacy Policy
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.