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.
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
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
- Spring 3 MVC Interceptor tutorial
- Spring MVC: Save / Retrieve BLOB object with Hibernate
- How to change spring-servlet.xml filename
- Spring MVC: Multiple Row Form Submit using List of Beans
- Spring 3 MVC – Autocomplete with JQuery & JSON example
- Spring MVC + FreeMarker (FTL) Integration example
- Spring MVC HashMap Form Integration example
- Spring MVC Multiple File Upload example
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 <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.
Get our Articles via Email. Enter your email address.
This did not work when I tried it using Spring tool suite. The best I got was “resource unavailable”
The source code downloaded was incomplete. It looks like the .xml files are not right.
If I had been coding a servlet I would have been finished ten minutes after I started.
I wonder why Spring make things so hard. But then no one made money from simplicity.
I am getting resource not found error. i want to know if thr is something wrong in writing the code or is this some tomcat issue?
and what can be the resolution to this problem?
im sure of putting all the files whereever necessary only. but still im facing this issue. please help ASAP>
Thanks ….
wrong post
This is working fine. I was executed this example
Thanks for the post.
But, have you tested this?
I am getting the following problem.
“java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘command’ available as request attribute” and spring3
Hi, Check if you are getting to JSP page from Spring Controller’s showContacts() method. This method set the “command” object in ModelAndView object. Check if your implementation is same as above example.
This also breaks!
Stacktrace:] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘contact’ available as request attribute
Thanks for the post.
But, have you tested this?
I am getting the following problem.
“java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘command’ available as request attribute” and spring3
fed up with this. Moving for another tutorial.
ooooops
Extemely sorry. it was my mistake. It works now.
in which xml files the Contact is defined
Hi, I have a doubt regarding multiple beans. If I have a two beans and from view page i want to add the details in the two models of those beans. Then how can I do that please ……………give me a suggestion.
I have 6 fields and 4 of one bean and 2 of another bean in a JSP. I want to add them with single action.
Thanks… it is to learn….
This tutorial has been great so far. I followed it step by step and everything is working. I had some issues from inside of Eclipse initially – but I stopped and restarted the server and everything is working so far.
Hi i just downladed the code and its not working.
ia m getting this as warning in console
No mapping found for HTTP request with URI [/spring/contacts.html] in DispatcherServlet with name ‘spring’
and getting 404 in my web page
Hi Sachin,
i also faced same issue, but now its works.
make sure that you are specified “” in the spring-servlet.xml ——here org.training.web.controllers in you controller location. This is the one which tell the servlet where to look for annotated methods.
Try it, Wishes
Sreenivas Nair
Hi Sachin,
i also faced same issue, but now its works.
make sure that you are specified
in the spring-servlet.xml ——here org.training.web.controllers in you controller location. This is the one which tell the servlet where to look for annotated methods.
Try it, Wishes
Sreenivas Nair
This works perfectly for me. I been new to Spring but your tutorial approach is very clear.
I have questions though, how you know what RequestMapping params e.g. POST to use. Like you learn the syntax.. is it just by experience ? I find it difficult to learn all the viewResolver, I went into the package but found there are so many different classes in spring, do we have to learn all these by doing one by one ??// i hope you understood my question. I m trying to looking for something which is less cramming but more logical. In core java javap command use to do that for me.
Hi Neeraj, You can go through Spring MVC documentation to learn all nitty gritty about it: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html
And you learn by practice. The more you’ll code, the more you would understand the APIs. Just read the documentation, its quite comprehensive.
I downloaded the source, But while importing in eclipse It is saying “should convert maven legasy project”. I clicked “yes”. Even pom.xml is showing errors and not able to compile the code because dependencies not getting downloaded.
Please help me.
HI,
Please help me its urgent basis, and new to spring 3.0,when i was running the code in ecilpse IDE,error will code (WARNING: Servlet spring is currently unavailable) is come???????
Hi navi,
If you can give little more details about the error. It will be easier to solve ur problem.\
your articles is awesome!
thank you so much!
i’m getting error while executing this application
the error is java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet
i have added the following jar files to libraries
commons-logging.jar
jstl.jar
org.springframework.asm-3.0.0.RELEASE.jar
org.springframework.beans-3.0.0.RELEASE.jar
org.springframework.context-3.0.0.RELEASE.jar
org.springframework.core-3.0.0.RELEASE.jar
org.springframework.expression-3.0.0.RELEASE.jar
org.springframework.web-3.0.0.RELEASE.jar
org.springframework.web.servlet-3.0.0.RELEASE.jar
spring.jar
jstl-1.2.jar
spring-webmvc-1.0.1.jar
org.springframework.web.servlet-3.0.0.M3.jar
can anybody tel me the solution to this
post here or mail me @ sri460@gmail.com
i am passing a map thru modeAndView. That map contains 2 strings and a object I need to set attributes in only that object in jsp. How to do that.
Thank you very much comrade
You need to mention the component scan in *-servlet.xml… Please mention the package which includes your bean and controller.
Wow!! I didn’t know that Alt + shift + S, R command creates very amazing code!
Thank you for the eclipse tip!!
Hi, The tutorial looks perfect, it worked fine with me, however I have a question:
Why does the line forwards to contacts if our jsp is named “contact.html” ??
Using this approach everything is working while you specify all the fields, i.e. when you never leave a blank field. What happens when you leave a field blank. The whole data doesn’t get updated to DB. In my case I have attachement to be uploaded with a form. Which is not mandatory. If the user specifies a attachment the data is saved the file gets uploaded. And when the User doesn’t give any attachement and only need the data to be uploaded, the whole data doesn’t even get uploaded. Can you help?
very good tutorial
thank you
Hello
I dont find the way to export the css code into a .css file an link it from the .jsp. Could you help me?
Thanks
works fine no issue….
thanks a lot i was searching for a good tutorial to learn. i think i found one.
this is great post,,,helped me a lot.
thanks Viral
the only change i did to resolve is
@RequestMapping(“/contact.html”)
public ModelAndView showContacts() {
return new ModelAndView(“contact”, “command”, new Contact());
}
and removed all contacts to contact so my request mapping is /contact.html
it worked great
Many thanks
Thank you for the good How-To Viral. I too have had few issues, mainly with ContactController. In your code you are saying to have “contact.jsp” file but have the @RequestMapping set to /contacts. I think it would be best to just have “contacts.jsp” and change the new ModelAndView to use “contacts” as well to avoid confusion. Though it does help understand that the jsp name can be different from URL used by request. I also had to update ContactController to handle RequestMapping for “/”. I had to remove welcome-file-list from web.xml and add an index() method to my controller which will redirect to contacts.html. I was getting many errors when trying to call root of application.
List of changes I did:
In web.xml:
<servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>In ContactController.java:
@RequestMapping("/") public String index() { return "redirect:contacts.html"; }Remove welcome-file-list from web.xml
Remove index.jsp
Update showContacts() method to direct to contacts page:
@RequestMapping("/contacts") public ModelAndView showContacts() { return new ModelAndView("contacts", "command", new Contact()); }I will continue on to the Spring 3 MVC with Hibernate blog post. Thank you for your work!
You should test this with Spring 3 — i have imported your code into an IntelliJ MVC project — and this throws all kinds of exceptions — why the hell does Spring make submitting form data so difficul;t – Java servlets — piece of cake.
thanks Viral. this is a very good tutorial for the beginner. I started from the Helloworld application and everything is just going on smoothly. I appreciate. God bless in Jesus name!