Hibernate Validator merupakan reference implementation dari JSR 303 yang mengatur mengenai model metadata dan API untuk validasi JavaBean.
Tutorial ini akan menunjukkan cara melakukan validasi sebuah form web menggunakan Hibernate Validator pada aplikasi berbasis Spring MVC.
Pengimplementasiannya mudah, kita tinggal menambahkan annotation pada property dari sebuah Java Bean untuk menerapkan aturan validasinya. Untuk menggunakan Hibernate Validator kita perlu memasangnya terlebih dahulu pada classpath, library dapat didownload disini
Beberapa aturan yang akan kita terapkan pada tutorial ini adalah sebagai berikut :
1. @NotNull : nilai property tidak boleh kosong
2. @Length : digunakan untuk mengatur panjang minimal dan atau maksimal sebuah string
3. @Range : digunakan untuk mengatur rentang nilai yang dibolehkan
Untuk pembahasan yang lebih lengkap silahkan kunjungi dokumentasi resminya disini
file : Customer.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package com.agung.entity; import javax.validation.constraints.NotNull; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.Range; /** * * @author Agung Setiawan */ public class Customer { @NotNull(message = "Name cannot be empty") @Length(min = 5,message = "Name must be at least 5 characters long") private String name; @NotNull(message = "Age cannot be empty") @Range(min = 10,message = "Minimum Age is 10") private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } } |
Kita dapat membuat pesan error sendiri dengan menggunakan attribut “message”.
Agar dapat bekerja dengan Hibernate Validator, Spring MVC Controller perlu menggunakan annotation @Valid
file : CustomerController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.agung.controller; import com.agung.entity.Customer; 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; /** * * @author Agung Setiawan */ @Controller @RequestMapping("customer") public class CustomerController { @RequestMapping(value="signup",method = RequestMethod.GET) public String addNewCustomer(Model model){ model.addAttribute("customer",new Customer()); return "index"; } @RequestMapping(value = "signup",method = RequestMethod.POST) public String addCustomer(@Valid Customer customer, BindingResult result,Model model){ if(result.hasErrors()){ return "index"; }else{ model.addAttribute("customer",customer); return "done"; } } } |
Supaya Spring MVC ini mengenali annotation @Valid kita perlu menambahkan “mvc:annotation-driven” pada file konfigurasi
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd" > <context:component-scan base-package="com.agung.controller"/> <mvc:annotation-driven/> //harus di-enable supaya support @Valid <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> </beans> |
Untuk view kita gunakan jsp. Ada 2 view disini, pertama form untuk melakukan pendaftaran dan kedua halaman yang menujukkan pendaftaran berhasil.
Jika pendaftaran gagal maka akan ditampilkan kembali halaman form pendaftaran beserta pesan error.
file : index.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <style type="text/css"> .error{ color:red; } </style> <title>Welcome to Spring Web MVC project</title> </head> <body> <c:url var="url" value="/customer/signup" /> <form:form modelAttribute="customer" action="${url}" method="POST"> <table> <tr> <td>Name</td> <td>:</td> <td><form:input path="name" /></td> <td><form:errors class="error" path="name" /></td> </tr> <tr> <td>Age</td> <td>:</td> <td><form:input path="age"/></td> <td><form:errors class="error" path="age" /></td> </tr> <tr> <td colspan="3"><input type="submit" /></td> </tr> </table> </form:form> </body> </html> |
file : done.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Done!</h1> Name :${customer.name} </br> Age :${customer.age} </body> </html> |
Tampilan Data yang dimasukkan benar
Saya baru belajar Spring , cara melihat errornya gimana ya kalau di netbeans?
Kalau saya run munculnya
In-place deployment at D:\desktopjava\BelajarSpring\build\web
GlassFish Server 4, deploy, null, false
D:\desktopjava\BelajarSpring\nbproject\build-impl.xml:1075: The module has not been deployed.
See the server log for details.
BUILD FAILED (total time: 3 seconds)