Form Processing in Spring MVC 3 using Annotation

Spring MVC framework will really became most popular mvc framework in next decade. Spring java mvc framework provides a lot of facilities to the web developers to make development work faster and flexible. In this tutorial we will see how easy it is to process a form using spring mvc 3 with annotation driven controller. We will take a simple student registration form with some fields and will see how spring mvc process it.

Our requirements :

We are planning to organize a free speak contest in our college and need to create a registration form form providing an interface to the students for participating to the event.

We have to follow bellow steps to successfully implement our requirement :

  • First of all we have to a domain object or pojo class ( for holding form values provided by the user.
  • Then, we will configure our spring configuration file (app-config.xml) to adopt annotation driven configuration for spring mvc.
  • After that we will implement our controller class ( that will handle two types of request. One for showing the form to the user and another for processing the input data of form.
  • Then, we will create the form jsp page (registration.jsp) using spring mvc ui taglibs and a registration success page (success.jsp) for the form to confirm the input data in form.
  • After that we will see how to change the error message for data conversion in message resource file ( is a pojo class that will store input data for the form and work as a container for the form data. In spring mvc 3, this type of classes are called command classes. Command classes in spring java mvc framework are special classes that holds application data while processing the in controllers or holds form data. The following is the code in User class :

package com.raistudies.domain;

public class User {

    private String name = null;
    private  String standard = null;
    private int age;
    private String sex = null;
    // Setters and getters are omitted for making the code short.
    public String toString() {
        return "User [name=" + name + ", standard=" + standard + ", age=" + age
        + ", sex=" + sex + "]";

The command class contains four properties to hold registration form data. Here, you will notice that the age field is of type int, so there can be conversion error if user type any alphabet or special character in this field. We will also learn how to customize the conversion error using message resource and how to show the errors in the form page.


We have to add two lines to make mvc configuration annotation driven in our spring configuration file app-config.xml. The following is configuration in the file app-config.xml :

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

    <!-- Application Message Bundle -->
    <bean id="messageSource" class="">
        <property name="basename" value="/WEB-INF/messages" />
        <property name="cacheSeconds" value="3000" />

    <!-- Scans the classpath of this application for @Components to deploy as beans -->
    <context:component-scan base-package="com.raistudies" />
    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

    <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>

You can learn about <context:component-scan/> and <mvc:annotation-driven/> from previous post. One new thing you can see in this tutorial is “messageSource” bean class of spring mvc jar. This class provides message resources to the view. This class takes two parameters :

  1. basename : This parameter should specify the location of the message resource file.
  2. cacheSeconds : This parameter will specify, how much time should be taken by the ReloadableResourceBundleMessageSource class before reloading the messages.

Our controller class will handle two requests, one for showing the registration form and another is to handle the submitted form. So there will be two functions with the same request mapping url but the request type will be different. For showing the registration form the request type will be GET and for processing form data submission the request type will be POST. See the bellow code to understand how to specify request type and process form :

package com.raistudies.controllers;

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 com.raistudies.domain.User;

public class RegistrationController {

    public String showForm(ModelMap model){
        User user = new User();
        model.addAttribute("USER", user);
        return "registration";

    public String processForm(@ModelAttribute(value="USER") User user,BindingResult result){
            return "registration";
            System.out.println("User values is : " + user);
            return "success";

As, you can see the class is annotated with @RequestMapping(value=”/registration.htm”), It means all the methods in this class will handle the request for the url “/registration.htm”. showForm will handle the GET request type and will show the registration form. showForm also adds a new instance to the model map so that the new instance can be associated with the shown form. processForm method processes the form data. Here two new things you will learn :

  • @ModelAttribute(value=”USER”) : ModelAttribute annotation will tell spring mvc framework that the “USER” model instance should be assigned as an instance of User class and should be pass to the method processForm.
  • BindingResult result : Spring will find our if any error occur during the creation of User class instance from model instance “USER” and if any error came its description will be pass the method as BindingResult instance.

If there is any error present than it will show again the registration form and if there is no error then success page will be shown to the user.


registration.jsp will show, how spring mvc form tag will be used to show the form elements in jsp and how errors are shown to the user if any occur. Following is the code of registration.jsp :

<%@ page session="true" %>
<%@ taglib uri="" prefix="form"%>
<html xmlns="">
        <title>Hello World with Spring 3 MVC</title>
        <meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
        <h1>Registration Form</h1><br />
        <form:form commandName="USER">
                <tr><td colspan="2"><form:errors path="*" cssStyle="color : red;"/></td></tr>
                <tr><td>Name : </td><td><form:input path="name" /></td></tr>
                <tr><td>Standard : </td><td><form:input path="standard" /></td></tr>
                <tr><td>Age : </td><td><form:input path="age" /></td></tr>
                <tr><td>Sex : </td><td><form:select path="sex">
                        <form:option value="Male"/>
                        <form:option value="Female"/>
                <tr><td colspan="2"><input type="submit" value="Save Changes" /></td></tr>

Spring provided ui taglibs for form elements. <form:errors/> element shows form input errors and any other error associated with the form data. As an example, there is a field “age” in our form which should be an integer and if a user specify any character in the field then conversion will come and that error will be shown in the form.

We will use this file to override conversion error text for the field “age” and will show a user friendly error message. Here is the error message :

typeMismatch.age= Age Field does not contain invalid age. Please enter a number.

Deploy the war file of the project to the tomcat 6 and open the url in browser you will get following registration form :

Registration Form Processing Using Spring MVC 3

Registration Form Processing Using Spring MVC 3

Now, fill all the fields in form but in the field age enter any alphabet and click on “Save Changes” button, you will get following screen :

Form Bindind Error Example Spring MVC

Form Bindind Error Example Spring MVC

Then, fill all values correctly and click on “Save Changes” button you will get following success page with confirmation of values entered :

Registration Confirmation Page

Registration Confirmation Page

🙂 ……. Its all fun to work with Spring MVC From Processing. Happy Coding!!!!!!!!!!!!!!!!!

You can also download the example code for Spring MVC From Processing from bellow links :

Source : Download

Related Posts:

Leave a comment ?


  1. Heya i am for the first time here. I found this board and I find It really useful & it helped me out much. I hope to give something back and help others like you helped me. Regards,

  2. Great guide, Thanks!

    You could really improve it if you could find a native English speaker to proof read it.

  3. very helpful for beginners.

  4. User user = new User();
    Violates DI, isn’i it?

  5. Ahaa, its good dialogue concerning this article at this place at this web site, I have read all
    that, so now me also commenting here.

  6. Excellent Tutorial…:)

Leave a Comment Cancel reply

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>