Spring > Spring Validation Using Annotation

Spring Validation Using Annotation

In this example you will learn the changes you need to make to the previous validation example to make it work with Spring annotations. When using annotated controller class the validate() method will not be automatically called. The onSubmit() method will be called when the form is submitted. Here you need to first call the validate() method of the UserValidator class, then check for any error using the hasErrors() method, if there are any errors then, forward the user to the user registration form and dispaly the errors, if there are no errors then display the success page. Here is the UserController class.

package com.w3javaguide.web;

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.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.w3javaguide.domain.User;
import com.w3javaguide.service.UserService;
import com.w3javaguide.validator.UserValidator;

public class UserController {

	private UserService userService;
	private UserValidator userValidator;

	public UserController(UserService userService, UserValidator userValidator) {
		this.userService = userService;
		this.userValidator = userValidator;

	@RequestMapping(method = RequestMethod.GET)
	public String showUserForm(ModelMap model) {
		User user = new User();
		model.addAttribute("user", user);
		return "userForm";

	@RequestMapping(method = RequestMethod.POST)
	public String onSubmit(@ModelAttribute("user") User user,
			BindingResult result) {
		userValidator.validate(user, result);
		if (result.hasErrors()) {
			return "userForm";
		} else {
			return "redirect:userSuccess.htm";


Here the UserService and the UserValidator classes are injected using the @Autowired annotation. The Spring bean configuration file has the following entries.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
	<bean id="viewResolver" class="org.springframework.web.servlet.view. InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
    <bean id="messageSource" class=" ResourceBundleMessageSource" p:basename="messages" />
    <context:component-scan base-package="com.w3javaguide.web" />
    <bean id="userService" class="com.w3javaguide.service.UserServiceImpl" />
    <bean id="userValidator" class="com.w3javaguide.validator.UserValidator" />

You can download and try the example here.

Source :Download
War :Download
Contact Us  |  Copyright © 2012