Home > Java and Web > Spring MVC Form Validation Dengan Annotation

Spring MVC Form Validation Dengan Annotation

Goal dari post ini membuat simple form validation menggunakan Spring Validator. Untuk melakukan validasi domain model, Spring menyediakan Validator inteface. Untuk menggunakan Validator ini, setidaknya ada tiga langkah yang harus dilakukan.

  • Buat class validator untuk domain model dan impelement Validator interface.
  • Override supports(Class clazz) method.
  • Override alidate(Object target, Errors errors) method.

Mari kita mulai..ūüôā

Langkah 1: Buat model class  yang akan divalidasi ( Product.java )


import java.util.Date;

public class Product {
private int id;
private String name;
private int price;
private Date expired;

public Integer getPrice() {
return price;
}

public void setPrice(Integer price) {
this.price = price;
}

public Integer getId() {
return id;
}

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

public String getName() {
return name;
}

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

public void setExpired(Date expired) {
this.expired = expired;
}

public Date getExpired() {
return expired;
}
}

Langkah 2: Buat validator class yang men-implements Validator interface ( ProductValidator.java )

import java.util.Date;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import org.springframework.validation.ValidationUtils;

@Component
public class ProductValidator implements Validator {

@Override
public boolean supports(Class clazz) {
return Product.class.isAssignableFrom(clazz);
}

@Override
public void validate(Object target, Errors errors) {

ValidationUtils.rejectIfEmpty(errors, "id", "product.id.empty");
ValidationUtils.rejectIfEmpty(errors, "name", "product.name.empty");
ValidationUtils.rejectIfEmpty(errors, "price", "product.price.empty");

Product product = (Product) target;
Integer id = product.getId();
if (id <= 0 && id != null) {
errors.rejectValue("id", "product.id.less");
}

String name = product.getName();
if (name.length() < 5) {
errors.rejectValue("name", "product.name.less");
}
Integer price = product.getPrice();
if (price <= 0) {
errors.rejectValue("price", "product.price.less");
}

Date expired = product.getExpired();
if (expired.before(new Date())) {
errors.rejectValue("expired", "product.expired.less");
}
}
}

Rule validasi yang dibuat :

  • Field tidak boleh kosong
  • Field name minimal 5 karakter
  • Field id dan price tidak boleh lebih kecil dari 0
  • Field expired date tidak boleh kurang dari date hari ini

Buat file message.properties dan letakkan dibawah folder /WEB-INF ( di-example ini saya letakkan di  /WEB-INF/resource)

product.id.empty = Id tidak bisa kosong
product.id.less = Id tidak bisa <= 0
product.name.less = Name product tidak bisa kurang dari 5 karakter
product.name.empty = Name product tidak bisa kosong
product.price.less = Price product <= 0
product.price.empty = Price product tidak bisa kosong
product.expired.less = Product expired tidak bisa kurang dari hari ini

Tambahkan kode berikut ini pada dispatcherServlet.xml


<bean id="messageSource"
     class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
     p:basename="/WEB-INF/resource/messages" />

Langkah 3 : Buat custom date editor (DateEditor.java) untuk format expired date dan product editor (ProductEditor.java) untuk cast id dan price field dari empty / null menjadi 0

DateEditor.java

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.propertyeditors.CustomDateEditor;

public class DateEditor extends CustomDateEditor {

public DateEditor(DateFormat dateFormat, boolean allowEmpty) {
super(dateFormat, allowEmpty);
}

@Override
public void setAsText(String text) {
System.out.println("setAsText Method Date Editor");
try {
setValue(new SimpleDateFormat("dd/MM/yyyy").parse(text));
} catch (ParseException e) {
setValue(new Date());
}
}

@Override
public String getAsText() {
String s = "";
if (getValue() != null) {
System.out.println("getAsText Method Date Editor");
s = new SimpleDateFormat("dd/MM/yyyy").format((Date) getValue());
}
return s;
}
}

ProductEditor.java

import java.beans.PropertyEditorSupport;
import org.springframework.stereotype.Component;

@Component
public class ProductEditor extends PropertyEditorSupport {

@Override
public void setAsText(String text) {
System.out.println("setAsText method" + text);
Integer id;
if (text == null || text.equals("")) {
id = 0;
setValue(id);
} else {
id = Integer.parseInt(text);
setValue(id);
}
}

@Override
public String getAsText() {
System.out.println("getAsText method" + getValue().toString());
return this.getValue().toString();
}
}

Buat class binding (GlobalBindingInitializer.java) untuk meregister kedua custom editor tersebut.

import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;

@ControllerAdvice
public class GlobalBindingInitializer {

@Autowired
ProductEditor customEditor;

@InitBinder
public void binder(WebDataBinder binder){
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
dateFormat.setLenient(false);
DateEditor editor = new DateEditor(dateFormat, false);
binder.registerCustomEditor(Date.class, editor);

binder.registerCustomEditor(Integer.class, customEditor);

}
}

Langkah 4: Buat controller class (ProductController.java)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;

@Controller
public class ProductController {

@Autowired
ProductValidator customValidator;

@RequestMapping(value = "/showProductForm.do", method = RequestMethod.GET)
public ModelAndView showFormProduct() {

ModelAndView mav = new ModelAndView("ProductForm", "product",
new Product());
return mav;
}

@RequestMapping(value = "/addProduct.do", method = RequestMethod.POST)
public ModelAndView addProduct(@Valid Product product, BindingResult result) {

customValidator.validate(product, result);

if (result.hasErrors()) {

ModelAndView mav = new ModelAndView("ProductForm", "product",
product);
return mav;
} else {

ModelAndView mav = new ModelAndView("ProductDetail", "product",
product);
return mav;
}
}
}

Langkah 5: Buat JSP view

ProductForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="form" 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Product Form</title>
<style>
.error {
color: #ff0000;
font-style: italic;
}
</style>
</head>
<body>
<form:form action="addProduct.do" method="post" commandName="product">
<table>
<tr>
<td>Id Product</td>
<td><form:input path="id"></form:input></td>
<td><form:errors path="id" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>Product Name</td>
<td><form:input path="name"></form:input></td>
<td><form:errors path="name" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>Product Price</td>
<td><form:input path="price"></form:input></td>
<td><form:errors path="price" cssClass="error"></form:errors></td>
</tr>

<tr>
<td>Expired Date(dd/MM/yyyy)</td>
<td><form:input path="expired"></form:input></td>
<td><form:errors path="expired" cssClass="error"></form:errors></td>
</tr>
<tr>
<td>
<input type="submit" value="Submit" />
</td>
</tr>

</table>
</form:form>
</body>
</html>

ProductDetail.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"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!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>Detail Product</title>
</head>
<body>
Detail Product <br>
Product Id      : ${product.id} <br>
Product Name    : ${product.name} <br>
Product Price   : ${product.price} <br>
Product Expired : <fmt:formatDate pattern="yyyy-MM-dd" value="${product.expired}" />
<br>
</body>
</html>

Result example :

Spring MVC Form Validation (1/3)

Spring MVC Form Validation (1/3)

Spring MVC Form  Validation (2/3)

Spring MVC Form Validation (2/3)

Form Validation (3/3)

Form Validation (3/3)

Referensi : dari berbagai sumber.

Semoga bermanfaat.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: