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.

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

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



38 Comments

  • raghu wrote on 6 July, 2010, 20:04

    Thanks for that spring3.0 applications. Can u provide the spring3.0 Group authorization example

  • stunaz wrote on 7 July, 2010, 9:30

    thanks, can you provide the same thing with internationalization?

  • Derrick wrote on 7 July, 2010, 17:01

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

  • raghu wrote on 12 July, 2010, 12:45

    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.

  • tuong wrote on 31 July, 2010, 17:24

    Can you please explain why do we need to use the annotation @SessionAttributes here?

    • Assem wrote on 16 March, 2011, 16:48

      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.

  • George wrote on 20 September, 2010, 9:36

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

  • Tun_Java wrote on 27 September, 2010, 0:02

    Thank you.
    so useful tutorial.
    It’s little bit different to develop with different IDE but in deed it’s Okay.

  • Tun_Java wrote on 27 September, 2010, 18:56

    Thank you.
    Great job !!!

  • know1stranger wrote on 1 October, 2010, 18:29

    Thanks man…! Awesome help you did

  • Nirwana wrote on 3 November, 2010, 21:02

    This is one of the great series of Spring MVC 3 tutorials. Thanks for putting it up.

  • Assaduzzaman wrote on 8 December, 2010, 13:53

    Hi this example is cool. It is possible to list all .jar list which is require to run this example.

  • stepan wrote on 22 December, 2010, 14:12

    Would you please show an example of CRUD controller?
    A have a problem with UPDATE of entity.

    • samantha wrote on 18 March, 2011, 22:20

      Please, have you make CRUD controller ? for UPDATE. I cannot do it. Can you explain me ?

  • sruthi wrote on 28 December, 2010, 0:56

    good for beginners! thanks a lot

  • Sristi wrote on 31 January, 2011, 17:32

    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

  • nitin wrote on 17 February, 2011, 12:44

    excellent ……work by your team….

  • SA wrote on 20 March, 2011, 2:43

    Getting following error, please help?
    No WebApplicationContext found: no ContextLoaderListener registered?

  • Madhu wrote on 16 April, 2011, 9:59

    Simple and precise example. Good work.

  • Ramanath wrote on 13 May, 2011, 16:36

    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

  • Medloh wrote on 25 May, 2011, 23:28

    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?

  • Medloh wrote on 25 May, 2011, 23:34

    Arg! Blog not showing my code, trying again:
    Changed index.jsp from

    &GT;jsp:forward page=”contact.html”$LT;&GT;/jsp:forward&LT;

    &GT;a href=”hello.html”&LT;Say Hello&GT;/a&LT;
    &GT;br/&LT;

    This doesn’t work, WHY???
    &GT;a href=”contacts.html”&LT;Contact Form&GT;/a&LT;

  • Rossen Stoyanchev wrote on 8 June, 2011, 15:47

    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!

  • mohammed rehan rizvi wrote on 21 June, 2011, 11:18

    Hi.. Is it possible to configure multiple forms (each having different command object) on the same page .?

  • Gourav wrote on 27 July, 2011, 20:09

    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

    • Bolat wrote on 9 August, 2011, 16:45

      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.

  • Shawn Z wrote on 2 August, 2011, 22:12

    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

  • leon wrote on 8 August, 2011, 11:32

    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.

  • leon wrote on 8 August, 2011, 11:42

    may i just ask. what is this parameter for? “BindingResult result”

  • sina wrote on 12 August, 2011, 6:22

    thatz very nice! please provide some example on use spring framework tags on name space sf for example and etc..
    thANKS AGAIN

  • Maruf wrote on 24 September, 2011, 0:07

    You give me start of Spring……You are my first spring boss…Thanks

  • Tito wrote on 6 November, 2011, 19:52

    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.

  • Francis wrote on 14 November, 2011, 17:03

    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…

  • Indra wrote on 15 December, 2011, 1:33

    very elaborate tutorial keep up the good work, its inspiring indeed , thanks a ton !

  • Hardeep wrote on 12 January, 2012, 14:45

    good job

  • Phillis wrote on 16 January, 2012, 22:05

    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

  • Suhas wrote on 24 January, 2012, 15:20

    Great tuts.

  • gleeb wrote on 30 January, 2012, 1:26

    This is just awesome!
    Thanks.

Leave a Reply

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

*

Copyright © 2012 ViralPatel.net. All rights reserved.