Tutorial: Working with Spring 3 MVC and HTML Forms

Post to Twitter

In my previous Spring 3 MVC tutorial I showed you how easy it is to work with the Spring Framework MVC. Today I’m going to take that tutorial a step further and show you one way you can work with HTML forms.


Note: To follow along better make sure you have read my previous Spring 3 MVC tutorial.

I’ll be assuming you have the following installed:

Java JDK installed
SpringSource Tool Suite – I downloaded the installer version – not the plug-in to Eclipse.

Run the SpringSource Tool Suite and create a new project: File -> New -> Spring Template Project

Add a new JSP file to the project under the views folder:

myform.jsp content:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="f"%>
<%@ page session="false" %>
<html>
<head>
    <title>Spring MVC Forms</title>
</head>
<body>
	<strong>Post a Message</strong>
		<f:form method="post" action="displayusermessage" commandName="usermessage">
		    <table>
			    <tr>
			        <td><f:label path="name">Name</f:label></td>
			        <td><f:input path="name" /></td>
			    </tr>
			    <tr>
			        <td><f:label path="message">Message</f:label></td>
			        <td><f:input path="message" /></td>
			    </tr>
			    <tr>
			        <td colspan="2">
			            <input type="submit" value="Post Message!"/>
			        </td>
			    </tr>
			</table> 
		</f:form>
</body>
</html>

This is a simple form that collects a name and a message to publish, it then posts the data to the displayusermessage.jsp file (which we will create shortly).

Now create a new Java package to hold a UserMessage class:

Inside of the new package add a UserMessage.java file:

UserMessage.java content:

package com.giantflyingsaucer.springmvcforms.form;

public class UserMessage {
	private String name;
	private String message;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
}

Create one more JSP file called displayusermessage.jsp in the views folder just like we did for the myform.jsp file:

displayusermessage.jsp content:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
	<title>Spring MVC Forms</title>
</head>
<body>
<h1>
	<strong><c:out value="${usermessage.name}"></c:out></strong> said: <c:out value="${usermessage.message}"></c:out>
</h1>
</body>
</html>

Here we simply print out the name and message that will be passed from the myform.jsp page.

The last thing to do is modify the HomeController.java file:

package com.giantflyingsaucer.springmvcforms;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.giantflyingsaucer.springmvcforms.form.UserMessage;


@Controller
public class HomeController {

	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	@RequestMapping(value="/", method=RequestMethod.GET)
	public String home() {
		return "redirect:myform";
	}
	
	@RequestMapping(value="/myform", method=RequestMethod.GET)
	public void myform(Model model) {
		model.addAttribute("usermessage", new UserMessage());
	}	
	
    @RequestMapping(value = "/displayusermessage", method = RequestMethod.POST)
    public void display(@ModelAttribute("usermessage") UserMessage usermessage, Model model) {    	
        model.addAttribute("usermessage", usermessage);
    }	
}

When someone hits the site we redirect them to myform which displays the page to collect the name and message. Once the page has been submitted they are sent to displayusermessage and the data is displayed.

Deploy your project and run it to test it out.

Use this address: http://localhost:8080/SpringMVCForms/

You should see this:

Thats it. Of course this is very minimal so make sure to read the docs to take this a step further to add things like validation, persistence, etc.

Post to Twitter

This entry was posted in Java. Bookmark the permalink.

2 Responses to Tutorial: Working with Spring 3 MVC and HTML Forms

  1. Pingback: The 5 minute tutorial to getting started with Spring 3 MVC | Giant Flying Saucer

  2. Everett says:

    This is a great example. Can you add in one more row in the application, say country? The row country is a drop down selection list, pre-filled with a few countries, but it can not be listed in the jsp. You can implemented the country like this:

    public class Country {

    private int countryId;
    private String countryName;

    public Country(int countryId, String countryName)
    {
    this.countryId=countryId;
    this.countryName=countryName;
    }

    public int getCountryId() {
    return countryId;
    }
    public void setCountryId(int countryId) {
    this.countryId = countryId;
    }
    public String getCountryName() {
    return countryName;
    }
    public void setCountryName(String countryName) {
    this.countryName = countryName;
    }
    }

    Please show how you inject the country list into the usermessage cammand. I just got stuck on this step.

    Thanks.

Comments are closed.