Spring 3 MVC: Handling Forms in Spring 3.0 MVC

[ad name=”AD_INBETWEEN_POST”] Welcome to the Part 3 of Spring 3.0 MVC Series. In previous article we created a Hello World application in Spring MVC. We leaned how to configure Spring MVC in web.xml and how to use different annotations like @Controller, @RequestMapping etc. In this article let us see how to handle forms in Spring 3.0 MVC.

We will use the framework that we created in previous article as a base reference and add up the functionality of form in it. Also the application that we create will be a Contact Manager application.

Related: Spring 3 MVC: Multiple Row Form Submit using List of Beans

Our Goal

Our goal is to create basic Contact Manager application. This app will have a form to take contact details from user. For now we will just print the details in logs. We will learn how to capture the form data in Spring 3 MVC.

Getting Started

Let us add the contact form to our Spring 3 MVC Hello World application. Open the index.jsp file and change it to following:

File: WebContent/index.jsp

<jsp:forward page="contacts.html"></jsp:forward>

The above code will just redirect the user to contacts.html page.

The View- contact.jsp

Create a JSP file that will display Contact form to our users.
File: /WebContent/WEB-INF/jsp/contact.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
	<title>Spring 3 MVC Series - Contact Manager</title>
<h2>Contact Manager</h2>
<form:form method="post" action="addContact.html">

		<td><form:label path="firstname">First Name</form:label></td>
		<td><form:input path="firstname" /></td> 
		<td><form:label path="lastname">Last Name</form:label></td>
		<td><form:input path="lastname" /></td>
		<td><form:label path="lastname">Email</form:label></td>
		<td><form:input path="email" /></td>
		<td><form:label path="lastname">Telephone</form:label></td>
		<td><form:input path="telephone" /></td>
		<td colspan="2">
			<input type="submit" value="Add Contact"/>

Here in above JSP, we have displayed a form. Note that the form is getting submitted to addContact.html page.

Adding Form and Controller in Spring 3

We will now add the logic in Spring 3 to display the form and fetch the values from it. For that we will create two java files. First the Contact.java which is nothing but the form to display/retrieve data from screen and second the ContactController.java which is the spring controller class.

File: net.viralpatel.spring3.form.Contact

package net.viralpatel.spring3.form;

public class Contact {
	private String firstname;
	private String lastname;
	private String email;
	private String telephone;
	//.. getter and setter for all above fields.

The above file is the contact form which holds the data from screen. Note that I haven’t showed the getter and setter methods. You can generate these methods by pressiong Alt + Shift + S, R.

File: net.viralpatel.spring3.controller.ContactController

package net.viralpatel.spring3.controller;

import net.viralpatel.spring3.form.Contact;

import org.springframework.stereotype.Controller;
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 org.springframework.web.servlet.ModelAndView;

public class ContactController {

	@RequestMapping(value = "/addContact", method = RequestMethod.POST)
	public String addContact(@ModelAttribute("contact")
							Contact contact, BindingResult result) {
		System.out.println("First Name:" + contact.getFirstname() + 
					"Last Name:" + contact.getLastname());
		return "redirect:contacts.html";
	public ModelAndView showContacts() {
		return new ModelAndView("contact", "command", new Contact());

In above controller class, note that we have created two methods with Request Mapping /contacts and /addContact. The method showContacts() will be called when user request for a url contacts.html. This method will render a model with name “contact”. Note that in the ModelAndView object we have passed a blank Contact object with name “command”. The spring framework expects an object with name command if you are using <form:form> in your JSP file.

Also note that in method addContact() we have annotated this method with RequestMapping and passed an attribute method=”RequestMethod.POST”. Thus the method will be called only when user generates a POST method request to the url /addContact.html. We have annotated the argument Contact with annotation @ModelAttribute. This will binds the data from request to the object Contact. In this method we just have printed values of Firstname and Lastname and redirected the view to cotnacts.html.

That’s all folks

The form is completed now. Just run the application in eclipse by pression Alt + Shift + X, R. It will show the contact form. Just enter view values and press Add button. Once you press the button, it will print the firstname and lastname in sysout logs.

Download Source Code

Click here to download source code (7.43kb)

Moving on

In this article we learn how to create a form using Spring 3 MVC and display it in JSP. Also we learn how to retrieve the form values using ModelAttribute annotation. In next section we will go through form validations and different data conversion methods in Spring 3 MVC.

Related: Spring 3 MVC Multiple Row Form Submit example

Get our Articles via Email. Enter your email address.

You may also like...


  1. Aishwarya.k says:

    The type java.lang.Object cannot be resolved. It is indirectly referenced from
    required .class files.get this error when i download the source code.

  2. Vidhi Shah says:

    This example is fine. But I am facing some problem. When I leave the browser IE8 ideal for sometime and then try to get form values in controller it is giving me null.
    Can you advise what can be done here?

  3. Alex says:

    But where is the addContact.html file??

    • omar says:

      there is no addContact.html
      you use the mapping in the controller class as follow:

      @RequestMapping(value = “/addContact”

  4. Raj says:

    How do you solve if you have entity one to many relationship form such as User and Addresses.
    Lets say user enter firstname, lastname and address fields. But as per user entity address is set or list. do you have some tutorial?

  5. quest says:

    WOW! very useful, thanks

  6. Gaurav Palkar says:

    The post is useful Viral Thanks, but I was getting resaurce not available error when I used to click on ‘Add Contact’ button. My application was not root application. When I change the form action to //addContact.html then I could see first name and last name on the console.

  7. Gaurav Palkar says:

    correction in the above post I changed to /springmvc/addContact.html then It worked

  8. Abel Souza says:

    This tutorial is great, but it lacks some information. I do not know if it was about my Spring version, but I had to add some code in order to avoid the following code:

    java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘Contact’ available as request attribute

    It happened because if the modelAttribute of <form:form is not available while the form is rendering. then the exception will raise. In order to fix it, just add the following code to the ContactControll class:

    public Contact loadEmptyModelBean(){
    return new Contact();

    Hopefully it will be useful to someone : )

  9. Vivek Soni says:

    What if I want to bind two objects ?
    Here in this example you are binding form values to contact object , what if I want to bind two objects ?

  10. reader says:

    I tried exeuting your code but —–http 404 error contacts.html not found…..I replaced contacts.html by contact.jsp still the same http 404 error

    • DaryaMarkova says:

      I have the same trouble)) Had you solved this problem? I am sorry for my English(

Leave a Reply

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