Spring mvc adding HIbernate form validation support

To enable Hibernate form validation support to your spring-mvc project we need some jars, Add the below dependencies to your existing maven pom and update your maven project. run the application by downloading the source code provided and check the control flow and how every thing is validated.

Updated this in Pom.xml


<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.1.Final</version>
</dependency>

home.jsp


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<p><a href="${pageContext.request.contextPath}/offers">Show current offers.</a></p>
<p><a href="${pageContext.request.contextPath}/createoffer">Add a new offer.</a></p>

</body>
</html>

OffersController.java


package com.sourceforopensource.spring.web.controllers;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.sourceforopensource.spring.web.dao.Offer;
import com.sourceforopensource.spring.web.service.OffersService;

@Controller
public class OffersController {
 
 private OffersService offersService;
 
 @Autowired
 public void setOffersService(OffersService offersService) {
 this.offersService = offersService;
 }
 
 @RequestMapping(value="/test", method=RequestMethod.GET)
 public String showTest(Model model, @RequestParam("id") String id) {
 System.out.println("Id is: " + id);
 return "home";
 }
 
 @RequestMapping("/offers")
 public String showOffers(Model model) {
 
 List<Offer> offers = offersService.getCurrent();
 
 model.addAttribute("offers", offers);
 
 return "offers";
 } 
 
 @RequestMapping("/createoffer")
 public String createOffer(Model model) {
 
 model.addAttribute("offer", new Offer());
 
 return "createoffer";
 }
 
 @RequestMapping("/docreate")
 public String doCreate(Model mode,@Valid Offer offer, BindingResult result) {
 
 
 if(result.hasErrors()){
 
 return "createoffer"; 
 }
 
 
 return "offercreated";
 }
}


createoffer.jsp


<%@ page language="java" contentType="text/html; charset=US-ASCII"
 pageEncoding="US-ASCII"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>

 <link href="${pageContext.request.contextPath}/static/css/main.css" rel="stylesheet" type="text/css" />

<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Insert title here</title>
</head>
<body>


<sf:form method="post" action="${pageContext.request.contextPath}/docreate" commandName="offer"> 
<table class="formtable">
<tr><td class="label">Name: </td><td><sf:input class="control" path="name" name="name" type="text"/><br><sf:errors path="name" cssClass="error"></sf:errors></td></tr>
<tr><td class="label">Email: </td><td><sf:input class="control" path="email" name="email" type="text"/><br><sf:errors path="email" cssClass="error"></sf:errors></td></tr>
<tr><td class="label">Your offer: </td><td><sf:textarea class="control" path="text" name="text" rows="10" cols="10"></sf:textarea><br><sf:errors path="text" cssClass="error"></sf:errors></td></tr>
<tr><td class="label"> </td><td><input class="control" value="Create advert" type="submit"/></td></tr>
</table>
</sf:form>

<! -- with the sf: attribute we are giving the form backend values remained even though the form is refreshed. we are making
making this form backed by Offer object.-- >

</body>
</html>

Offer.java


package com.sourceforopensource.spring.web.dao;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

public class Offer {
 private int id;
 
 
 @Size(min=5, max=100, message="Name must be between 5 and 100 chatacters")
 private String name;
 
 @NotNull
 @Pattern(regexp=".*\\@.*\\..*", message="This does not appear to be a vaid email address")
 private String email;
 
 @Size(min=5, max=100, message="Text must be between 5 and 250 chatacters")
 private String text;
 
 
 public Offer() {
 
 }

 public Offer(String name, String email, String text) {
 this.name = name;
 this.email = email;
 this.text = text;
 }
 
 

 public Offer(int id, String name, String email, String text) {
 super();
 this.id = id;
 this.name = name;
 this.email = email;
 this.text = text;
 }

 public int getId() {
 return id;
 }

 public void setId(int id) {
 this.id = id;
 }

 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public String getEmail() {
 return email;
 }

 public void setEmail(String email) {
 this.email = email;
 }

 public String getText() {
 return text;
 }

 public void setText(String text) {
 this.text = text;
 }

 @Override
 public String toString() {
 return "Offer [id=" + id + ", name=" + name + ", email=" + email
 + ", text=" + text + "]";
 }

}


output:

If any input is wrong according to our validation rules given to Offer.java
the below errors will get.

Hibernate validation api example result

Hibernate validation api example result

Download

The complete source code is here offers – with hibernate validation support

Balakrishna Pendyala

Author: Balakrishna Pendyala

Balakrishna is a Software Engineer working in Media Streaming Domain, and also worked on Banking and Health Care domains. His areas of interest include Object Oriented Design, SOLID Design principles, Restful Web Services and Open Source softwares including Spring, Spring Boot, and Hibernate.

If you found an error, highlight it and press Shift + Enter or click here to inform us.

Leave a Reply

Your email address will not be published. Required fields are marked *