Meyyappan has posted 101 posts at DZone. View Full User Profile

Spring Form Tags Tutorial

06.15.2012
| 132713 views |
  • submit to reddit

In this example you will see how to populate the form with dynamic values. Here is the user registration form.

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Registration Page</title>
</head>
<body>

<form:form method="POST" commandName="user">
<table>
    <tr>
        <td>User Name :</td>
        <td><form:input path="name" /></td>
    </tr>
    <tr>
        <td>Password :</td>
        <td><form:password path="password" /></td>
    </tr>
    <tr>
        <td>Gender :</td>
        <td>
            <form:radiobutton path="gender" value="M" label="M" /> 
            <form:radiobutton path="gender" value="F" label="F" />
        </td>
    </tr>
    <tr>
        <td>Country :</td>
        <td>
            <form:select path="country">
            <form:option value="0" label="Select" />
            <form:options items="${countryList}" itemValue="countryId" itemLabel="countryName" />
            </form:select>
        </td>
    </tr>
    <tr>
        <td>About you :</td>
        <td><form:textarea path="aboutYou" /></td>
    </tr>
    <tr>
        <td>Community :</td>
        <td><form:checkboxes path="communityList" items="${communityList}" itemValue="key" itemLabel="value" /></td>
    </tr>
    <tr>
        <td></td>
        <td>
        <form:checkbox path="mailingList" label="Would you like to join our mailinglist?" />
        </td>
    </tr>
    <tr>
        <td colspan="2"><input type="submit" value="Register"></td>
    </tr>
</table>
</form:form>

</body>
</html>

 Here we populate the countryList and the communityList from the back-end. The items attribute holds the collection. The itemValue and itemLabel attributes holds the key and value respectively. ItemLabel is the one that will be displayed to the user and itemValue is the one that will be passed when that particular item is selected.

Here we have three domain objects User, Country and Community. The User object is the one that is associated with the form.

package com.vaannila.domain;

import java.util.List;

@SuppressWarnings("unchecked")
public class User {

	private String name;
	private String password;
	private String gender;
	private String country;
	private List countryList;
	private String aboutYou;
	private String[] community;
	private List communityList;
	private Boolean mailingList;
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
	public String getCountry() {
		return country;
	}
	public void setCountry(String country) {
		this.country = country;
	}
	public List getCountryList() {
		return countryList;
	}
	public void setCountryList(List countryList) {
		this.countryList = countryList;
	}
	public String getAboutYou() {
		return aboutYou;
	}
	public void setAboutYou(String aboutYou) {
		this.aboutYou = aboutYou;
	}
	public String[] getCommunity() {
		return community;
	}
	public void setCommunity(String[] community) {
		this.community = community;
	}
	public List getCommunityList() {
		return communityList;
	}
	public void setCommunityList(List communityList) {
		this.communityList = communityList;
	}
	public Boolean getMailingList() {
		return mailingList;
	}
	public void setMailingList(Boolean mailingList) {
		this.mailingList = mailingList;
	}
	
		
}

The User object has a countryList and communityList to hold the list of countries and communities respectively.

The countryList contains a list of Country objects.

ackage com.vaannila.domain;

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;
	}
	
}

The countryId is used to refer the country in the back-end and the countryName to dispaly the country in the front-end.

Similarly the communityList contains a list of community objects.

package com.vaannila.domain;

public class Community {

	private String key;
	private String value;
	
	public Community(String key, String value)
	{
		this.key = key;
		this.value = value;
	}
	
	public String getKey() {
		return key;
	}
	public void setKey(String key) {
		this.key = key;
	}
	public String getValue() {
		return value;
	}
	public void setValue(String value) {
		this.value = value;
	}
	
}

Here the value is the one that will be dispalyed in the front-end and the key is the one that will be used in the back-end.

In the controller class you need to override the referenceData() method. In this method you can set all the default values that should be loaded when the form is displayed to the user. This method will be called automatically.

package com.vaannila.web;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.vaannila.domain.User;
import com.vaannila.service.UserService;

@SuppressWarnings("deprecation")
public class UserController extends SimpleFormController {

	private UserService userService;

	public UserController()	{
		setCommandClass(User.class);
		setCommandName("user");
	}
	
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected Map referenceData(HttpServletRequest request) throws Exception {
		Map referenceData = new HashMap();
		referenceData.put("countryList", userService.getAllCountries());
		referenceData.put("communityList", userService.getAllCommunities());
		return referenceData;
	}

	@Override
	protected ModelAndView onSubmit(Object command) throws Exception {
		User user = (User) command;
		userService.add(user);
		return new ModelAndView("userSuccess","user",user);
	}

}

In the referenceData() method we first create a HashMap and add the countryList and the communityList to it. This method will be called before the form is rendered so the list will be populated before that.

When you run the example you will see the user registration form. On submitting the form the userSuccess.jsp page will be displayed. In the userSuccess.jsp page we use jstl tags to display the details.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Success Page</title>
</head>
<body>
User Details
<hr>
User Name   : <c:out value="${user.name}"></c:out> <br/>
Gender      : <c:out value="${user.gender}"></c:out> <br/>
Country     : <c:out value="${user.country}"></c:out> <br/>
About You   : <c:out value="${user.aboutYou}"></c:out> <br/>
Community   : 
<c:forEach var="community" items="${user.communityList}" >
	<c:out value="${community}"></c:out>
</c:forEach> <br />
Mailing List: <c:out value="${user.mailingList} "></c:out>
</body>
</html>

You can download and try the example here.

Source :Download
War :Download
Published at DZone with permission of its author, Meyyappan Muthuraman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Ankit Tiwari replied on Sun, 2013/06/16 - 1:10pm

 Good basics of spring form tags.

Varun Tiwari replied on Tue, 2014/07/22 - 7:15am

this is very nice example to understand but why you are extending a specific SimpleFormController, do i need to remember different controllers for different working.Please reply .


Thanks

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.