• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring MVC Form Handling Example

November 24, 2014 by javainterviewpoint 4 Comments

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 from the user, processes the input and finally returns a response back to the user. Let’s 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 startup 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 different requests “displayForm” and “Register” under that we implement two methods “Welcome()” and “processRegistration()” let’s see each of the methods 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 makes 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”.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> 

 <servlet>
 <servlet-name>SpringConfig</servlet-name>
 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>SpringConfig</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>
</web-app>

Spring Configuration File

 <beans xmlns="http://www.springframework.org/schema/beans" 
xmlns:context="http://www.springframework.org/schema/context" 
xmlns:mvc="http://www.springframework.org/schema/mvc" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation=" http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
 
 <context:component-scan base-package="com.jackson"></context:component-scan>
 <mvc:annotation-driven/>
 
 <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
 <property name="prefix" value="/WEB-INF/Jsp/"></property>
 <property name="suffix" value=".jsp"></property>
 </bean>
 
 </beans>

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

Other interesting articles which you may like …

  • context:annotation-config vs context:component-scan
  • Spring MVC BeanNameUrlHandlerMapping Example
  • Spring MVC ControllerClassNameHandlerMapping Example
  • Spring MVC SimpleUrlHandlerMapping Example
  • Spring MVC Flow Diagram
  • Spring MVC Multiple submit buttons in a single form
  • Spring MVC SimpleFormController Example
  • Spring 4 – Spring MVC Hello World Example
  • Spring REST Hello World Example – JSON and XML responses
  • ClassNotFoundException: org.springframework.web.context.ContextLoaderListener
  • Fix missing src/main/java folder in Eclipse Maven Project – 2 build path entries are missing
  • Spring MVC CRUD Example with MySql + JdbcTemplate

Filed Under: J2EE, Java, Spring, Spring MVC, Spring Tutorial Tagged With: Form Handling, Spring MVC, Spring MVC Form Handling, Spring MVC framework, Spring Web Framework, Spring Web MVC framework

Comments

  1. Arun Sundaramoorthy says

    August 30, 2018 at 9:47 pm

    Very nice explanation.

    Reply
  2. harshavardhan says

    June 27, 2019 at 2:19 pm

    you didn’t mention what to write in SpringConfig-servlet.xml and web.xml files

    Reply
    • javainterviewpoint says

      June 28, 2019 at 11:52 am

      Added the configuration files

      Reply
  3. Ashish Sanu says

    March 18, 2020 at 11:14 pm

    for anyone referring this page note that commandName in jsp is deprecated better use ModelAttribute

    Reply

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·