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″]
Requirement:
Springframework 2.5 or latest
[/googlefont]

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;

	@NotNull
	@NotEmpty
	private String firstname;

	@NotNull
	@NotEmpty
	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;

@Controller
@RequestMapping("VIEW")
public class TutorialController {

	@Autowired
	private PersonService service;

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

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

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

	@ActionMapping
	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 {
                     service.save(form);  
	             response.setRenderParameter("action", "success");		
		}
	}

	@ModelAttribute("person")
	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"/>
	</div>
</form:form>

4) Configure application-context

<context:annotation-config/>
<mvc:annotation-driven/>
<bean id="annotationMethodHandlerAdapter" 
class="org.springframework.web.portlet.mvc.annotation.AnnotationMethodHandlerAdapter">
   <property name="webBindingInitializer">
      <bean 
         class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
	   <property name="validator">
	      <ref bean="validator"/>
	   </property>
      </bean>
   </property>
</bean>

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

portletvalidation

 

 

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

<bean id="messageSource"
    class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
  <property name="defaultEncoding" value="UTF-8"/>
  <property name="cacheSeconds" value="7200"/>
  <property name="basenames">
           <value>classpath:messages</value>
  </property>
</bean>

 

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 {

@Valid
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.