Quantcast
Channel: Kruders.com » Spring MVC
Viewing all articles
Browse latest Browse all 10

Spring and Tag

$
0
0

In this example, you will learn how to create a HTML radio button with Spring <form:radiobutton> tag. For Example :

<form:radiobutton path="fruit" value="Apple" />Apple 
<form:radiobuttons path="hobbies" items="${hobbiesList}" />

You can create a single radiobutton using <form:radiobutton> tag or a group of radiobuttons created at runtime using <form:radiobuttons> tag

In order to use the Spring Form Tags you need to include the following taglib directive in the jsp page.

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

First create a new Dynamic Web Project and configure it as Maven Project. For Reference, Click Here

  <properties>
	<spring.version>3.1.0.RELEASE</spring.version>
  </properties>
  <dependencies>

	<!-- Spring 3 dependencies -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-core</artifactId>
		<version>${spring.version}</version>
	</dependency>

	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>${spring.version}</version>
	</dependency>

	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>taglibs</groupId>
		<artifactId>standard</artifactId>
		<version>1.1.2</version>
	</dependency>
	<dependency>
		<groupId>jstl</groupId>
		<artifactId>jstl</artifactId>
		<version>1.1.2</version>
	</dependency>
  </dependencies>

1. Model

Following is the Person class.

package com.kruders.domain;

public class Person {
	String hobbies;
	String fruit;
	String password;
	public String getHobbies() {
		return hobbies;
	}
	public void setHobbies(String hobbies) {
		this.hobbies = hobbies;
	}
	public String getFruit() {
		return fruit;
	}
	public void setFruit(String fruit) {
		this.fruit = fruit;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

2. Controller

In order to handle spring forms, you need your controller to extend SimpleFormController. Following class shows you how to extend SimpleFormController

PersonController.java

package com.kruders.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

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

import com.kruders.domain.Person;

public class PersonController extends SimpleFormController{
	public PersonController(){
		setCommandClass(Person.class);
		setCommandName("personForm");
	}
	
	@Override
	protected Object formBackingObject(HttpServletRequest request) throws Exception {
 		Person person = new Person();
 		person.setHobbies("Gardening");
 		return person;
 	}
	
	@Override
	protected ModelAndView onSubmit(Object command) throws Exception {
		Person person = (Person) command;
		return new ModelAndView("personSuccess","person",person);
	}
	
	
	protected Map referenceData(HttpServletRequest request) throws Exception {
 
		Map referenceData = new HashMap();
		List<String> hobbiesList = new ArrayList<String>();
		hobbiesList.add("Gardening");
		hobbiesList.add("Listening Music");
		hobbiesList.add("Writing Technical Tutorials");
		referenceData.put("hobbiesList", hobbiesList);
 
		return referenceData;
 
	}
}

3. Form Validation

To validate the form fields we have a seperate PersonValidator class that implements the Validator interface, override the validate() method perform all the validations.

Following in the PersonValidator class.

package com.kruders.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.kruders.domain.Person;

public class PersonValidator implements Validator{
	@Override
	public boolean supports(Class<?> clazz) {
		return Person.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		Person person = (Person) target;
		ValidationUtils.rejectIfEmptyOrWhitespace(errors,"hobbies", "hobbies.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "fruit", "fruit.required");
	}
}

4. Properties File

A properties file to store all the error messages. Here we have the error messages in a seperate properties file so we add the error code, you can even add the error messages directly.

messages.properties

hobbies.required = Select at least one hobby
fruit.required = Select at least one fruit

5. View

Following is the form person form that contains Spring’s Form Tags and display error message if any.

form:errors tag to dispaly errors in jsp files.

personForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
	pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring &lt;form:checkboxes&gt; Checkbox</title>
<style>
.error {
	color: red;
}
 
</style>
</head>
<body>
<form:form method="POST" commandName="personForm">
	<table>
		<tr>
			<td>Fruits :</td>
			<td>
				<form:radiobutton path="fruit" value="Apple" />Apple 
				<form:radiobutton path="fruit" value="Mango" />Mango
			</td>
			<td><form:errors path="fruit" cssClass="error" /></td>
		</tr>
		<tr>
			<td>Hobbies :</td>
			<td>
				<form:radiobuttons path="hobbies" items="${hobbiesList}" />
			</td>
			<td><form:errors path="hobbies" cssClass="error" /></td>
		</tr>
	</table>
	<tr>
			<td colspan="3"><input type="submit" value="Submit"></td>
		</tr>
</form:form>
</body>
</html>

On successful submission of personform, personSuccess.jsp page will be displayed.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Output</title>
</head>
<body>
Fruits :
<c:forEach items="${person.fruit}" var="fruit">
		<c:out value="${fruit}" /> <br/>
</c:forEach>
<br />
Hobbies :<br />
<c:forEach items="${person.hobbies}" var="hobby">
		<c:out value="${hobby}" /> <br/>
</c:forEach>
<br />
</body>
</html>

6. Spring Bean Configuration

We now declare the controller and validator for the personform Spring Bean Configuration file.

	<bean class="com.kruders.controller.PersonController">
		<property name="formView" value="personForm" />
		<property name="successView" value="personSuccess" />
	 
		<!-- Map a validator -->
		<property name="validator">
			<bean class="com.kruders.validator.PersonValidator" />
		</property>
 	</bean>

Also add the properties file.

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" p:basename="messages" />

7. Run

Now when you run the project, following screen will be displayed as in Figure 65.1

Figure 65.1 Figure 65.1


Now when you select some radio button and click submit button, following screen will be displayed as shown in Figure 65.2

Figure 65.2 Figure 65.2

You can download the source code of this example here.



Viewing all articles
Browse latest Browse all 10

Trending Articles