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



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

    • prabhakar tiwari 8 August, 2013, 10:55

      For using this application,first make sure you are using the Exact jar files which are given there in hello world example.even the version no. and A.jar and jar files have some difference.moreover in eclipse i think you should go to build path and there click on”Add External jars” and select “servlet api.jar”.I think it will be helpful..

  • 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

    • Jim 16 August, 2013, 19:34

      Contact is not defined in an xml file. It is a POJO that Spring wires as a bean.

  • 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

    • prabhakar tiwari 8 August, 2013, 10:59

      I would like to suggest you that any difference in jar files makes difference.In google all jars with all versions are available.You use exactly the same jars which are given there in the hello world example.they will surely work for you.

      • Jim 16 August, 2013, 2:07

        doesn’t work with 3.0.5 jars

  • 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!

  • somnath 10 June, 2013, 16:42

    Can you tell how I can set default value in above forms???

    • Viral Patel 10 June, 2013, 16:51

      You can pass the default value to form in the controller method showContacts() in ContactController class. We are setting a new Contact() object as command object. Instead of that you can pass Contact object having default values. Something like below:

      @RequestMapping("/contacts")
      public ModelAndView showContacts() {
              
      	Contact contact = new Contact();
      	contact.setFirstname("John");
      	contact.setLastname("Lock");
      	return new ModelAndView("contact", "command", contact);
      }
      
  • Subrat Kumar 23 June, 2013, 8:38

    Hi…
    this program run successfully.but i have some doubt..like @ModelAttribute(“contact….)
    what is the necessity for that..

  • Diksha 11 July, 2013, 10:04

    great tutorial , thanks

  • udit 15 July, 2013, 15:22

    Plz post tutorial/example of “Form validations and different data conversion methods in Spring 3 MVC”, I couldn’t find it on your site.
    Thanks.

  • Umanath 29 July, 2013, 16:31

    I had an array of elements How to pass this data to spring 3.0.
    Model
    String stuName;
    Int time;
    String sub;
    Stu Time subject Time subject Time subject
    Stu1 9 Maths 10 Sci 11 Eng
    Stu2 9 Maths 10 Sci 11 Eng
    Stu3 9 Maths 10 Sci 11 Eng
    Stu4 9 Maths 10 Sci 11 Eng

    Here you pass list of data.It really helpful.
    But i try to pass list of list data. How to pass this data? Thank you in advance

  • Mike 3 August, 2013, 7:23

    I can’t get this to work. I’m getting the error No mapping found for HTTP request with URI [/Spring3MVC2/contact.html] in DispatcherServlet with name ‘spring’

  • Mike 3 August, 2013, 9:34

    I get an 404 error when trying to run this, anyone have any ideas why

  • Praveen 7 August, 2013, 16:17

    Please make sure that the jsp file name ‘contact.jsp’ and the mapping in ModelAndView(“contact”, “command”, new Contact()) are same.

    Here the action given like ‘contacts’ and the file name given like ‘contact’. But it won’t make any problem anyway but be ensure that the mapping is correct.

  • Kiran 8 August, 2013, 12:11

    Hi Viral,
    Very nice tutorial i got. Hello world application worked for me. Really thanks for this application also. I changed the Request mapping url as

     
    @RequestMapping(value="/contacts.html")
    	public ModelAndView showContacts()
    	{
    		
    		return new ModelAndView("contacts" , "command" , new Contact());
    	}
    

    and acordingly i changed jsp name to ‘contacts.jsp’
    But i am facing some issue while running the project. I am getting the error again n again.SEVERE: Servlet.service() for servlet jsp threw exception
    java.lang.ClassNotFoundException: org.springframework.web.util.ExpressionEvaluationUtils.

    Please help to resolve the thing. Thanks.

  • Soheb 19 September, 2013, 15:29

    have a question, i have 2 tabs and have corresponding VOs, in both tab, there is a link summary that will display the data from both VO (summary is readonly screen, no inputs required).

    In my controller i have placed a method as

    @RequestMapping(value = "/summaryProduct", method = RequestMethod.GET)
        public ModelAndView viewProductSummary() {
            Map<String, Object> model = new HashMap<String, Object>();
            model.put("basicDetailsProduct", productVO
                    .getBasicDetailsProductVO());
            model.put("additionalDetailsProduct", productVO
                    .getAdditionalDetailsProductVO());
            return new ModelAndView("SummaryProduct", "model", model);
        }

    But in summary screen, fields remain null. summary.jsp

    <label class="formHeading">${model.basicDetailsProduct.prodDesc}</label>

    ProductVO has both screen’s VO and all are in session in spring-servlet.xml.

    Can you please help me with this?

  • priya 30 September, 2013, 18:59

    i m creating an application. the 1st pag of my app is a login pg. When i give the usernam n pwd and give submit , i get
    ” 404 The requested resource (/Project1/connectionDetail) is not available.”
    Its not getting navigated to the nxt pg .
    This is my controller class:

    public class ConnectionController {
    	@RequestMapping(value = "/login", method = RequestMethod.GET)
    	   public ModelAndView login(){		
    		ModelAndView mv = new ModelAndView("login","command",new ConnectionDetails());
    		mv.setViewName("login");	
    		return mv;
    	}
    	
    @RequestMapping(value="/connectionDetail",method = RequestMethod.POST)
    public String ConnectionDetails(ModelMap model,@Valid @ModelAttribute("log_det")LoginBean log_det,BindingResult result){
    	System.out.println("name"+log_det.getUsername());
    	model.addAttribute("lusername",log_det.getLUsername());
    	model.addAttribute("lpassword",log_det.getLPassword());	
    	return "connectionDetail";
    }}
    

    Please help ASAP.

  • Miltee 13 November, 2013, 22:46

    I think “method will render a model with name “contact”. Note that in the ModelAndView object we have passed” … this confused me at first. Did you mean to say “render a view” ?

  • Leigh 23 November, 2013, 9:57

    Fix the issue that “java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name”
    Hope the solution is helpful.

    In Contact.jsp file
    1. Add commandName

    2. Add

  • Deepak 23 December, 2013, 18:05

    Awsome Tutorial….Cannot miss a Thing….!! and the Best part is you have Part -by part Download….Keep it up…

  • ms 10 January, 2014, 15:10

    hai viral

    can we use plain HTML form instead of JSP ?

  • Bartosz Zak 5 February, 2014, 15:45

    Hello,

    I hope you will see my reply.

    There is an error (not critical) on this page in contact.jsp file.
    You have 4 input forms there and three of them have the same path = “lastname”. It’s not causing an error because you never use them, but it will be good to fix that (well, basic example shouldn’t have such error).

    Best,
    Bartek

  • Pingpong 10 February, 2014, 7:35

    @Viral Patel

    Very good website.

    What about authentication and authorization in MVC? Any good books on MVC you can recommend?

  • Sasasd 21 February, 2014, 21:45

    Tx for your tutorials, they r really helpful!
    Iv found some minor errors:

    Email

    Telephone

  • wang bo 24 February, 2014, 7:59

    Using session when every request… Not correct.
    Is this a kind of miss-use?

  • Mckenzie 1 March, 2014, 16:13

    Thanks a lot for these wonderfulllllllll examples !!

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]