Spring 3 MVC: Handling Forms in Spring 3.0 MVC
- By Viral Patel on July 5, 2010
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.
Related: Spring 3 MVC: Multiple Row Form Submit using List of Beans
Spring 3.0 MVC Series
- Part 1: Introduction to Spring 3.0 MVC framework
- Part 2: Create Hello World Application in Spring 3.0 MVC
- Part 3: Handling Forms in Spring 3.0 MVC
- Part 4: Spring 3 MVC Tiles Plugin Tutorial with Example in Eclipse
- Part 5: Spring 3 MVC Internationalization & Localization Tutorial with Example in Eclipse
- Part 6: Spring 3 MVC Themes in Spring-Tutorial with Example
- Part 7: Create Spring 3 MVC Hibernate 3 Example using Maven in Eclipse
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.
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"%> <html> <head> <title>Spring 3 MVC Series - Contact Manager</title> </head> <body> <h2>Contact Manager</h2> <form:form method="post" action="addContact.html"> <table> <tr> <td><form:label path="firstname">First Name</form:label></td> <td><form:input path="firstname" /></td> </tr> <tr> <td><form:label path="lastname">Last Name</form:label></td> <td><form:input path="lastname" /></td> </tr> <tr> <td><form:label path="lastname">Email</form:label></td> <td><form:input path="email" /></td> </tr> <tr> <td><form:label path="lastname">Telephone</form:label></td> <td><form:input path="telephone" /></td> </tr> <tr> <td colspan="2"> <input type="submit" value="Add Contact"/> </td> </tr> </table> </form:form> </body> </html>
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;
@Controller
@SessionAttributes
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";
}
@RequestMapping("/contacts")
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
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.
Get our Articles via Email. Enter your email address.
Thanks for that spring3.0 applications. Can u provide the spring3.0 Group authorization example
thanks, can you provide the same thing with internationalization?
Very nice tutorials, etc.
I also think it’d be nice if you show a “List View” of the contacts. After you submit the new contact form, you are taken back to the list of contacts, with a status message of “New contact added”.
No need to use tomcat. Spring providing the one of the tool is like SpringSourceTool. We can download this tool use it. Its very easy.
Can you please explain why do we need to use the annotation @SessionAttributes here?
the @SessionAttributes typically list the names of contact attributes which should be transparently stored in the session or some conversational storage, serving as form-backing beans.
This tutorials have made it very easy for me to learn spring 3.They are really good…..I haven’t found better ones on line.Thank you!!!
Thank you.
so useful tutorial.
It’s little bit different to develop with different IDE but in deed it’s Okay.
Thank you.
Great job !!!
Thanks man…! Awesome help you did
This is one of the great series of Spring MVC 3 tutorials. Thanks for putting it up.
Hi this example is cool. It is possible to list all .jar list which is require to run this example.
Would you please show an example of CRUD controller?
A have a problem with UPDATE of entity.
Please, have you make CRUD controller ? for UPDATE. I cannot do it. Can you explain me ?
good for beginners! thanks a lot
How to display the properties of two entities in a single form using form tags?
How to get the value of a specific attribute using form tag?
Please Help.
Its urgent
Regards,
Sristi
excellent ……work by your team….
Getting following error, please help?
No WebApplicationContext found: no ContextLoaderListener registered?
Simple and precise example. Good work.
Hi,
I am getting the following exception while trying to open the form:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘example’ available as request attribute
Any idea on how to bind commandName using Spring web mvc 3?
Thanks
Ramanath
Nice tutorial. Question. Trying to get a better understanding of the SpringMVC plumbing: I changed index.jsp from
to
Say Hello
Contact Form
Clicking on hello link works. But when I click on the contacts link I get some error about spring servlet having no mapping for it. I don’t understand why, it looks like the defs defined in the XML should handle this. Could someone explain why this doesn’t work?
Arg! Blog not showing my code, trying again:
Changed index.jsp from
>jsp:forward page=”contact.html”$LT;>/jsp:forward<
>a href=”hello.html”<Say Hello>/a<
>br/<
This doesn’t work, WHY???
>a href=”contacts.html”<Contact Form>/a<
Hi- nice series. Just one minor comment. I would encourage making the most of the flexible method signature. So rather than:
@RequestMapping(“/contacts”)
public ModelAndView showContacts() {
return new ModelAndView(“contact”, “command”, new Contact());
}
Have this:
@RequestMapping(“/contacts”)
public String showContacts(Model model) {
model.addAttribute(“command”, new Contact());
return “contact”;
}
Further, you could rely on built-in naming conventions. If the JSP was called “contacts.jsp” and the form had model=”contact” then your method would be even shorter:
@RequestMapping(“/contacts”)
public void showContacts(Model model) {
model.addAttribute(new Contact());
}
Small point but certainly readability counts!
Cheers!
Hi.. Is it possible to configure multiple forms (each having different command object) on the same page .?
Hi
i am facing the some problem with the simple hello world application. The problem is that when i am returing the ModelAndView object from my controller servlet, it is not picking the view name from that. But if return him simple file name rather then ModelAndView Object it will directly take me to that file name.
eg
@RequestMapping(“/RequestComing”)
public ModelAndView sayHello(){
String msg=”test”;
return new ModelAndView(“responseGoing”,”message”,msg);
}
if i use the above code then it will search for RequestComing.htm rather then responseGoing.jsp
the xml file contain
please help me to come out from this
Dear Gourav, my post didn’t come out properly, hence, I am re-posting it with slight amendments:
check your xml configurations. I assume that your web.xml has:
*.htm in the servlet-mapping section
This is the mapping to controllers. That is, all requests from the browser ending .htm will be forwarded to the appropriate conroller. In your case, it should be sayHello() as you have defined the mapping of @RequestMapping(“/RequestComing”). The point made here is that the extension *.htm, searches for the controller, NOT jsps.
And I assume in your spring-context.xml it has something like:
… property name=”suffix” value=”.jsp”
which means that the returned sring name from the controllers, in your case, upon sayHello() returnining the ModelAndView(“responseGoing”,”message”,msg) will appended the .jsp (as defined in spring-context.xml) to “responseGoing”, that is, it will then look for responseGoing.jsp.
Hence, from what you have written it appears that it is not searching for the jsp in question, but rather, it is actually searching for the controller sayHello() as you have mapped it with @RequestMapping(“/RequestComing”). Solution: is to make sure all the configurations are correct and the controllers (java files) and the jsps are stored in the correct directory structure.
Cutting and pasting that does not work in MVC3. To get the extension to work, I had to create a class file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace incMvcSite.Classes {
public static class HtmlPrefixScopeExtensions {
public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix) {
return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
}
private class HtmlFieldPrefixScope : IDisposable {
private readonly TemplateInfo templateInfo;
private readonly string previousHtmlFieldPrefix;
public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix) {
this.templateInfo = templateInfo;
previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
}
public void Dispose() {
templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;
}
}
}
}
In the Razor (.cshtml) file, I added the following:
@using incMvcSite.Classes
@using(Html.BeginHtmlFieldPrefixScope(“Permission”)) {
Permission
// The Html.EditorFor’s would go here…
}
Notice the using to bring me extension class into scope. That allows the second using line to work.
Now the problem is that when posting back, the object is not updated. In my controller, I used a second parameter to specify my prefix:
TryUpdateModel(modelUser.Permission, “Permission”);
This added the prefix to all field in the HTML, and the TryUpdateModel loaded the object with prefixed control names. Now you can properly namespace your controls for embedded edit lists, and for partial views of models with the same property names.
Shawn Zernik
Internetwork Consulting
thanks for posting this article. it gave me an idea on how spring works! but before making it work i really had to understand first how and why the codes are made.
may i just ask. what is this parameter for? “BindingResult result”
thatz very nice! please provide some example on use spring framework tags on name space sf for example and etc..
thANKS AGAIN
You give me start of Spring……You are my first spring boss…Thanks
wowwww….i cant tell how happy im.. thank u for ur great tutorial.. i went a step further to deploy this spring mvc app in google app engine.. yay.. thank u..keep up ur good work..itz coz of programmers like u who can share the knowledge and that too in an easy way..that budding developers like me can learn things fast and easy.
I am currently facing difficulty in running the tutorials even the previous one “Hello World”. Everytime when i try to run, i keep getting this error “The requested resource (/Spring3MVC/contacts) is not available.” and for the previous hello world program i get this “The requested service (Servlet spring is currently unavailable) is not currently available.” as an error.
Can someone throw in some light into this…I am very much stuck and new to Web Development…
very elaborate tutorial keep up the good work, its inspiring indeed , thanks a ton !
good job
New to Java EE and these are some great tutorials.
Had an issue with “//.. getter and setter for all above fields.” as I had no idea I had to do anything but download file gives working code.
Cheers
Great tuts.
This is just awesome!
Thanks.