Spring mvc portlet form annotation validation

In this tutorial I’ll show you how to use the annotation way to validate your form in portlet with spring mvc.

[googlefont font=”Courgette” fontsize=”12″]
Springframework 2.5 or latest

1) Create model and annotated validation.

package com.codeomitted.validation.model;
import java.io.Serializable;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;

public class Person implements Serializable {

	private static final long serialVersionUID = 1L;

	private String id;

	private String firstname;

	private String lastname;

	public Person() {

        // getter setter omitted


2) Create Controller with RenderMapping and ActionMapping. When form is posting will send to validate, if the requirement are not met. It will add the errors into the model map and send back to default render mapping.

package com.codeomitted.validation.controller;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.portlet.bind.annotation.ActionMapping;
import org.springframework.web.portlet.bind.annotation.RenderMapping;

public class TutorialController {

	private PersonService service;

	public String view(ModelMap model) {
		model.put("test", "test");
		model.put("list", service.getlist());
		return "index";

	public String showPerson(
                            RenderRequest request, 
			    RenderResponse response, ModelMap map) {

		Errors errs = (Errors) map.get("errors");
		if(errs != null) {
			map.addAttribute("errors", errs);
		return "index";

	public void doSearch(@Valid @ModelAttribute("person") Person form,
                             BindingResult bindingResult, 
			     ActionRequest request, 
                             ActionResponse response, 
                             ModelMap map) throws Exception

		if(bindingResult.hasErrors()) {
		     for(ObjectError err : bindingResult.getAllErrors()) {
			map.addAttribute("errors", bindingResult);
			response.setRenderParameter("action", "");		
		}else {
	             response.setRenderParameter("action", "success");		

	public Person getCommandObject(){
		return new Person();		


3) Create view

// code omitted
<portlet:actionURL var="postUrl" />

<form:form action="${postUrl}" method="post" commandName="person">
     <form:errors path="*" cssClass="errorClass" />
	ID <form:input path="id"/> <br/>
	Fistname: <form:input path="firstname"/> 
                  <form:errors path="firstname" cssClass="errorClass" />
	Lastname: <form:input path="lastname"/> 
                  <form:errors path="lastname" cssClass="errorClass" />

	<div class="button">
	     <input type="submit" value="Save"/>

4) Configure application-context

<bean id="annotationMethodHandlerAdapter" 
   <property name="webBindingInitializer">
	   <property name="validator">
	      <ref bean="validator"/>

<bean id="validator" 
  class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean" />




5) Customize your error message with locale support. Configure message resolve bundle

<bean id="messageSource"
  <property name="defaultEncoding" value="UTF-8"/>
  <property name="cacheSeconds" value="7200"/>
  <property name="basenames">


6) From your message.properties file, override the message. Such as

NotNull=I dont want to be null
NotEmpty=Don't let me empty please
Min=Hey, that is min value


7) For specific field custom localize message just put the dot with field name. Example

NotNull.firstName=I dont want to be null
NotEmpty.lastName=Don't let me empty please
Min.age=Hey, that is min age value


8) Last things, if you have one-to-one or one-to-many object, Let’s say, Parent and Children class, you may required to add @Valid annotation to perform validation recursively on the associated object.

public class Parent {

private Children children;

// code omitted
Spring mvc portlet form annotation validation

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.