Spring 3 MVC: Handling Forms in Spring 3.0 MVC

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.
spring-3-contact-manager-form

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.
contact-form-package-spring-mvc

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.
spring-3-contact-manager-form

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



94 Comments

  • alexK 9 September, 2012, 18:45

    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.

  • Praj 23 September, 2012, 16:25

    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 ….

    • Anup 10 October, 2012, 12:07

      wrong post

      • kiran 13 March, 2013, 18:48

        This is working fine. I was executed this example

  • Pandian 12 October, 2012, 21:03

    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

    • Viral Patel 12 October, 2012, 22:59

      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.

  • Pandian 14 October, 2012, 1:10

    This also breaks!

    Stacktrace:] with root cause
    java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name ‘contact’ available as request attribute

    • Gireesh 13 December, 2012, 19:41

      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

  • Pandian 14 October, 2012, 1:27

    fed up with this. Moving for another tutorial.

  • Pandian 14 October, 2012, 1:47

    ooooops
    Extemely sorry. it was my mistake. It works now.

  • JavaRam 17 October, 2012, 16:11

    in which xml files the Contact is defined

  • aswin kumar 20 October, 2012, 1:52

    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.

  • Ruman 25 October, 2012, 16:31

    Thanks… it is to learn….

  • Dennis Stevens 29 October, 2012, 5:16

    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.

  • Sachin 8 November, 2012, 12:30

    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

    • Sreenivas Nair 14 November, 2012, 14:57

      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

    • Sreenivas Nair 14 November, 2012, 14:59

      Hi Sachin,
      i also faced same issue, but now its works.
      make sure that you are specified

       &lt;context:component-scan base-package=&quot;org.training.web.controllers&quot; /&gt;

      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

  • Neeraj 12 December, 2012, 9:54

    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.

  • Ramesh 12 December, 2012, 22:21

    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.

  • navi 14 December, 2012, 22:41

    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???????

  • Mohan 20 December, 2012, 10:29

    Hi navi,
    If you can give little more details about the error. It will be easier to solve ur problem.\

  • ish128 21 December, 2012, 15:30

    your articles is awesome!
    thank you so much!

  • srinivas 29 December, 2012, 17:56

    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

  • ajinkya 23 January, 2013, 17:26

    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.

  • Dimitri 2 February, 2013, 7:23

    Thank you very much comrade

  • Anirudha Sen 7 February, 2013, 19:04

    You need to mention the component scan in *-servlet.xml… Please mention the package which includes your bean and controller.

  • David Lee 12 February, 2013, 14:14

    Wow!! I didn’t know that Alt + shift + S, R command creates very amazing code!

    Thank you for the eclipse tip!!

  • Aarón 26 February, 2013, 10:09

    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” ??

  • Debopam Mitra 8 March, 2013, 11:21

    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?

  • Pulkit Gupta 11 March, 2013, 15:46

    very good tutorial
    thank you

  • Juien 10 April, 2013, 19:07

    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

  • hemant 16 April, 2013, 15:01

    works fine no issue….
    thanks a lot i was searching for a good tutorial to learn. i think i found one.

  • Jagruti 16 April, 2013, 15:40

    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

  • CW 1 May, 2013, 9:12

    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!

  • Scott 17 May, 2013, 9:12

    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.

  • Kehinde 20 May, 2013, 14:34

    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!

Leave a Reply

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

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]