Spring MVC Form Handling Example

In this following example we will learn how to write a simple web based application which makes use of HTML forms using Spring Web MVC framework. Create a Dynamic Web Application in Eclipse to develop a Dynamic Form based Web Application using Spring Web Framework. In this example the user fills in a web form and click Submit button. The server receives the request of the user, processes the input and finally returns a response back to the user. Lets go ahead and see how the Spring MVC framework supports form handling.

Folder Structure :

  1. Create a Dynamic Web Project RegistrationForm and create a package for our src files “com.javainterviewpoint
  2. Place the Spring 3 jar files under WEB-INF/Lib 
  3. Put the index.jsp under the WebContent directory.
  4. Create the Java classes MVC_Controller.java and RegistrationBean.java under  com.javainterviewpoint folder.
  5. Place the SpringConfig-servlet.xml and web.xml  under the WEB-INF directory
  6. View files RegistrationForm.jsp and RegistrationSuccess.jsp are put under the sub directory under WEB-INF/Jsp

 Index.jsp

This is simply a start-up page which redirects the user to our RegistrationForm.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
 <a href="displayForm.html">Click here to Register</a>
</body>
</html>

RegistrationForm.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>Insert title here</title>
</head>
<body>
 <form:form action="Register" method="POST" commandName="rb">
 <table>
 <tr>
 <td>Name</td>
 <td><form:input path="name"/></td>
 </tr>
 <tr>
 <td>Age</td>
 <td><form:input path="age"/></td>
 </tr>
 <tr>
 <td>Profession</td>
 <td><form:select path="profession" items="${professionList}"></form:select></td>
 </tr>
 <tr>
 <td><input type="submit" value="Register"/></td><td></td>
 </tr>
 </table>
 </form:form>
</body>
</html>

When the user clicks on the link “Click here to Register” the controller will redirect the user to our RegistrationFrom.

Here <form:form> plays vital role, which is similar to that of the HTML <form> tag, you could see a special attribute called commandName=”rb”, where rb act as the form-backing object.

All the form tags <form:input>,<form:select>  has a particular attribute called path, this specifies the name of a property of the model class (RegistrationBean.java)

MVC_Controller.java

package com.javainterviewpoint;
	
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
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.servlet.ModelAndView;
	
	@Controller
	public class MVC_Controller 
	{
		@ModelAttribute("professionList")
		public List populateProfession()
		{
			List professionList = new ArrayList();
			professionList.add("Developer");
			professionList.add("Manager");
			professionList.add("Architect");
			
			return professionList;
		}
		@RequestMapping("/displayForm")
		public ModelAndView Welcome()
		{
			return new ModelAndView("RegistrationForm","rb",new RegistrationBean());
		}
		@RequestMapping(value="/Register",method=RequestMethod.POST)
		public String processRegistration(@ModelAttribute("rb")RegistrationBean rb)
		{
			System.out.println(rb.getName());
			return "RegistrationSuccess";
		}
	}

We can see the Controller (@Controller annotated) is designed to handle two differnent requests “displayForm” and “Register” under that we implement two methods “Welcome()” and “processRegistration()” lets see each of the method in the controller class in detail.

  • Welcome()

This method does nothing but simply redirecting to the RegistrationForm.jsp returns the ModelAndView object which has three parameters

          return new ModelAndView("RegistrationForm","rb",new RegistrationBean());

1. View component to be redirected to, here the RegistrationForm.jsp is the view component.

2. key for the form-backing object.

3. Value for the key.

  • processRegistration():

This method handles POST request when the form gets submitted. The key parameter here is

                   @ModelAttribute("rb")RegistrationBean rb

The @ModelAttribute annotation binds the key “rb” and make it available to the body again,the key must match the commandName  in <form:form> tag of the RegistrationForm.jsp.

When the Form is submitted Spring will automatically map the values to the backing object and hence we can access the values directly like below

System.out.println(rb.getName());

Finally upon processing, the controller returns the Success view page “RegistrationSuccess”.

 One more important thing to be noted in the controller is @ModelAttribute(“professionList”) In the RegistrationForm.jsp we are dynamically populating the “profession” select box, the populateProfession() only returns the values on the screen when ${professionList} is hit.

RegistrationBean.java

package com.javainterviewpoint;

public class RegistrationBean 
{
	String name;
	int age;
	String profession;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getProfession() {
		return profession;
	}
	public void setProfession(String profession) {
		this.profession = profession;
	}
}

Our model has three fields such as the name,age,profession which binds to the corresponding fields in the view component (RegistrationForm.jsp) and hence it is called as form-backing object.

RegistrationSuccess.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!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>Insert title here</title>
</head>
<body>
<h1>Registration Successful!!</h1>
 <table border="1">
 <tr>
 <td>Name</td>
 <td>${rb.name}</td>
 </tr>
 <tr>
 <td>Age</td>
 <td>${rb.age}</td>
 </tr>
 <tr>
 <td>Profession</td>
 <td>${rb.profession}</td>
 </tr>
 </table>
</body>
</html>

This simply uses the JSP Expression Language to display the values of the model “rb”.

Testing our Application

Once the application is deployed on to the server, run with below url

http://localhost:9090/SpringMVCForms/

Spring_MVC_Form_Handling_index

 

Go ahead and click the hyperlink to get our form.

Spring_MVC_Form_Handling_RegistrationForm

Click on the Register button, we will get the success page as below.

Spring_MVC_Form_Handling_RegistrationSuccess

Hurray!! We have built our first Spring MVC based Registration Form

Leave a Reply

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