This is an example of how to make use of
Hibernate 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 how
hibernate validator works, we will make use of
Spring-MVC to create a simple form page. Each field in the form has a validation constraint set by the annotations provided by the
Hidernate validator package.
Our preferred development environment is
Eclipse. We are using Eclipse Juno (4.2) version, along with
Maven Integration plugin version 3.1.0. You can download Eclipse from
here and Maven Plugin for Eclipse from
here.
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 and
Spring MVC are inserted as dependencies thruough
Maven and
Tomcat 7 is the application server.
Let’s begin,
1. Create a new Maven project
Go to File -> Project ->Maven -> 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 is
unchecked, hit “Next” to continue with default values.
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.
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.
The Maven project structure is shown below:
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’s
pom.xml file, by editing it at the “Pom.xml” page of the POM editor. The dependencies needed are
spring-webmvc package, the
javax.validation and the
hibernate-validator packages:
pom.xml
03 | <modelVersion>4.0.0</modelVersion> |
04 | <groupId>com.javacodegeeks.snippets.enterprise</groupId> |
05 | <artifactId>springexample</artifactId> |
06 | <packaging>war</packaging> |
07 | <version>0.0.1-SNAPSHOT</version> |
08 | <name>springexample Maven Webapp</name> |
13 | <groupId>org.springframework</groupId> |
14 | <artifactId>spring-webmvc</artifactId> |
15 | <version>${spring.version}</version> |
19 | <groupId>javax.servlet</groupId> |
20 | <artifactId>servlet-api</artifactId> |
21 | <version>2.5</version> |
24 | <groupId>javax.validation</groupId> |
25 | <artifactId>validation-api</artifactId> |
26 | <version>1.1.0.Final</version> |
29 | <groupId>org.hibernate</groupId> |
30 | <artifactId>hibernate-validator</artifactId> |
31 | <version>5.1.0.Final</version> |
35 | <finalName>springexample</finalName> |
39 | <spring.version>3.2.9.RELEASE</spring.version> |
3. Create the model with the validation annotations
The
Form.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, the
min, max and the message 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. The
regex 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
01 | package com.javacodegeeks.snippets.enterprise.form.model; |
03 | import javax.validation.constraints.Min; |
04 | import javax.validation.constraints.NotNull; |
05 | import javax.validation.constraints.Pattern; |
06 | import javax.validation.constraints.Size; |
08 | import org.hibernate.validator.constraints.Length; |
09 | import org.hibernate.validator.constraints.Range; |
13 | @Size(min=5, max=10, message="Your name should be between 5 - 10 characters.") |
16 | @Min(value=5, message="Please insert at least 5 characters") |
17 | private String lastname; |
19 | @NotNull(message="Please select a password") |
20 | @Length(min=5, max=10, message="Password should be between 5 - 10 charactes") |
21 | private String password; |
23 | @Pattern(regexp="[0-9]+", message="Wrong zip!") |
26 | @Pattern(regexp=".+@.+\\..+", message="Wrong email!") |
29 | @Range(min=18, message="You cannot subscribe if you are under 18 years old.") |
32 | public String getName() { |
36 | public void setName(String name) { |
40 | public String getLastname() { |
44 | public void setLastname(String lastname) { |
45 | this.lastname = lastname; |
48 | public String getPassword() { |
52 | public void setPassword(String password) { |
53 | this.password = password; |
56 | public String getZip() { |
60 | public void setZip(String zip) { |
64 | public String getEmail() { |
68 | public void setEmail(String email) { |
72 | public String getAge() { |
76 | public void setAge(String age) { |
4. Create a controller
The
Controller is where the
DispatcherServlet 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.
The Controller consists of two basic methods, a GET method, which is
String initForm(Model model) and a POST method, which is
String submitForm(Model model, @Valid Form form, BindingResult result). The first method creates and returns to the
"form" view a new instance of the
Form.java class. The second method gets the
Form 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 the
Form.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 the
successForm.jsp page, and the form object is passed at the
Model. Otherwise, the returned String is the String representation of the
form.jsp page, which also has the error messages, as will be shown below.
FormController.java
01 | package com.javacodegeeks.snippets.enterprise.form; |
03 | import javax.validation.Valid; |
05 | import org.springframework.stereotype.Controller; |
06 | import org.springframework.ui.Model; |
07 | import org.springframework.validation.BindingResult; |
08 | import org.springframework.web.bind.annotation.RequestMapping; |
09 | import org.springframework.web.bind.annotation.RequestMethod; |
11 | import com.javacodegeeks.snippets.enterprise.form.model.Form; |
14 | @RequestMapping("/form.htm") |
15 | public class FormController { |
17 | @RequestMapping(method = RequestMethod.GET) |
18 | public String initForm(Model model) { |
19 | Form form = new Form(); |
20 | model.addAttribute("form", form); |
24 | @RequestMapping(method = RequestMethod.POST) |
25 | public String submitForm(@Valid Form form, BindingResult result) { |
26 | String returnVal = "successForm"; |
27 | if(result.hasErrors()) { |
5. Create a view
We make use of the
form:form tag. Its
method property is set to POST, and the
commandName property is set to the name of the backing bean that is binded to the Model, which is the
Form.java class.
The
form:input tag is used to create all the input fields, with its
path property set to every field binded to it. The
form:errors tag defines where the error message of the specified field will be displayed in the view. Finally, the
input tag, with
type property set to
submit is used for the submit button.
form.jsp
04 | <title>Spring MVC form submission</title> |
08 | <h2>Fill your form!</h2> |
10 | <form:form method="POST" commandName="form"> |
13 | <td>Enter your name:</td> |
14 | <td><form:input path="name" /></td> |
15 | <td><form:errors path="name" cssStyle="color: #ff0000;"/></td> |
18 | <td>Enter your lastname:</td> |
19 | <td><form:input path="lastname" /></td> |
20 | <td><form:errors path="lastname" cssStyle="color: #ff0000;" /></td> |
23 | <td>Enter your password:</td> |
24 | <td><form:input path="password" /></td> |
25 | <td><form:errors path="password" cssStyle="color: #ff0000;" /></td> |
28 | <td>Enter your zip:</td> |
29 | <td><form:input path="zip" /></td> |
30 | <td><form:errors path="zip" cssStyle="color: #ff0000;" /></td> |
33 | <td>Enter your email:</td> |
34 | <td><form:input path="email" /></td> |
35 | <td><form:errors path="email" cssStyle="color: #ff0000;" /></td> |
38 | <td>Enter your age:</td> |
39 | <td><form:input path="age" /></td> |
40 | <td><form:errors path="age" cssStyle="color: #ff0000;" /></td> |
43 | <td><input type="submit" name="submit" value="Submit"></td> |
When validation succeeds, the page below will be rendered:
successForm.jsp
3 | <title>Spring MVC form submission</title> |
7 | Form successfully submitted. |
6. Configure the application
The files that we must configure in the application are the
web.xml file and the
mvc-dispatcher-servlet.xml file.
7. Run the application
Now, let’s run the application. We first build the project with Maven and place the
.war file produced in
webapps 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:
As a result all validation messages are rendered. Now complete your form correctly and press on submit button:
The form is submitted sucessfully.