Spring - MVC Form Handling
Last Updated :
18 Feb, 2022
Prerequisites: Spring MVC, Introduction to Spring
Spring MVC is a Model-View-Controller framework, it enables the separation of modules into Model, View, and Controller and uniformly handles the application integration. In this article, we will create a student login form and see how Spring MVC handles form-based web-based applications.
Steps to Create a Spring MVC Student Form in Eclipse IDE
First, create a Maven project selecting maven-archetype-webapp as we are going to create a web application. Now, enter the Group Id as well as Artifact Id. This will create a maven project with a pom.xml configuration file which will look something like this:
Now, let's start with configuring the webapp to define and configure beans to create instances. In Spring MVC you need to add some configuration files to make your application work. Let's start by adding some dependencies into the pom.xml already created after creating a maven project. The pom.xml defines all the dependencies that maven has to get and manage for you.
XML
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gfg</groupId>
<artifactId>SpringMvcStudentForm</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<java.version>1.8</java.version>
</properties>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.15</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-orm -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.3.15</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMvcStudentForm</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using
Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
The root-context file in the "/src/main/webapp/WEB-INF/spring/root-context.xml" defines shared resources visible to all other web components. In this program, the root-context defines all spring beans and their transitive dependencies in an XML file.
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
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.xsd">
</beans>
Then web.xml file defines mapping with different URLs and servlets to handle requests for those URLs. In this configuration file, we have used listener for application startup, configured servlet, and added a servlet-mapping to map the URL. Notice that we have named the servlet gfg, which will come in use afterward.
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"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>gfg</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>gfg</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
</web-app>
Now we create a model class Student.java with fields such as name, id, and password. The class is created in the com.gfg.model package. The fields are bound to the corresponding fields on the view page.
Java
package com.gfg.model;
public class Student {
private String name;
private String id;
private String password;
// needed to create a new instance via reflection by
// your persistence framework.
public Student() { super(); }
// if you don't create an constructor then there is no
// need to provide an empty constructor.
public Student(String name, String id, String password)
{
super();
this.name = name;
this.id = id;
this.password = password;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getId() { return id; }
public void setId(String id) { this.id = id; }
public String getPassword() { return password; }
public void setPassword(String password)
{
this.password = password;
};
@Override public String toString()
{
return String.format(
"Student [name=%s, id=%s, password=%s]", name,
id, password);
}
}
The login.jsp defines the student login page components with the appropriate fields to match the student object, this file is located in the  "/src/main/webapp/WEB-INF/views/login.jsp".Â
HTML
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Student Login Form</title>
</head>
<body>
<form:form name="submitForm" method="POST">
<div align="center">
<table>
<tr>
<td>Student name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td>User id</td>
<td><input type="text" name="id" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
<div style="color: red">${error}</div>
</div>
</form:form>
</body>
</html>
This is the gfg-servlet.xml file located in  "/src/main/webapp/WEB-INF/gfg.servlet.xml". This file is named after the servlet-name we have mentioned in the web.xml file, it handles all HTTP requests for the web applications. The annotation-driven enable the spring @Controller function, resource-mapping helps in handling HTTP requests for all resources. The bean configuration helps in identifying and scanning the jsp located in the views folder. The component-scan locates and allocated beans according to the mentioned annotation.
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<resources mapping="/resources/**" location="/resources/" />
<annotation-driven />
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
</beans:bean>
<context:component-scan base-package="com.spring.controller" />
</beans:beans>
The controller class handles the business-related logic, it handles requests coming from the client ( In this case the browser ) and redirects them to the view page. The StudentController class invoked by using @Controller has two methods for two request, first one is studentLogin which allows a Get request using @GetMapping annotation it has Model as the parameter, the information and the data provided by the user is passed to the model interface which is then rendered and shown in the view, the second method is a Post request using @PostMapping which is used to create a new data in the database, but in this case, we are redirecting it to the success.jsp without saving the data and also validating the entered user id and password.
Java
package com.gfg.controller;
import com.gfg.model.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class StudentController {
@GetMapping(path = "/")
public String studentLogin(Model model)
{
model.addAttribute(
"var", "Please Enter Your Login Details");
return "login.jsp";
}
@PostMapping
public String
submitLogin(Model model,
@ModelAttribute("student") Student student)
{
if (student.getId() != null
& student.getPassword() != null) {
if (student.getId().equals("gfg")
&& student.getPassword().equals("123")) {
model.addAttribute("var",
student.getName());
return "success.jsp";
}
else {
model.addAttribute("error",
"Invalid Details");
return "login.jsp";
}
}
else {
model.addAttribute("error",
"Please enter Details");
return "login.js[";
}
}
}
After successful login the StudentController class will redirect the page to success.jsp file located in "/src/main/webapp/WEB-INF/views/success.jsp". This page has a very simple HTML written welcoming page.
HTML
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Success Form</title>
</head>
<body>
<font color="562789" align="center"><h1>Student Welcome page</h1></font>
<span>${var}</span> You have successfully logged in.
<font color="555555"><h1>Hope you have a great day !</h1></font>
</body>
</html>
After coding all classes and configuration file your project structure would look something like this:
Output:Â
Now It's time to run your project in tomcat, check out this link if you need help running a tomcat server. After successfully running the tomcat server type this link "http://localhost:8080/SpringMvcStudentForm/" in your favorite browser. (user id - "gfg" and password - "123")

So, we have created a very basic login form-based web application with Spring MVC and tested it locally in the tomcat server.
Similar Reads
Spring MVC - Multiple Controller
We may construct numerous controllers at once in Spring MVC. Each controller class must be annotated with the @Controller annotation. A Spring MVC example with numerous controllers can be found here. The procedure is as follows: In the case of Maven, load the spring jar files or add dependencies.Mak
2 min read
Spring MVC - Model Interface
The Spring Web model-view-controller (MVC) is an open-source framework used to build J2EE web applications. It is based on the Model-View-Controller design pattern and implements the basic features of a core spring framework - Dependency Injection. It is designed around a 'DispatcherServlet' that di
7 min read
Spring MVC - Number Validation
The Spring Web model-view-controller (MVC) is an open-source framework used to build J2EE web applications. It is based on the Model-View-Controller design pattern and implements the basic features of a core spring framework - Dependency Injection. It is designed around a 'DispatcherServlet' that di
9 min read
Spring - MVC Form Checkbox
In this article, we will learn about the Spring MVC Checkbox and Checkboxes tags. We will create a basic Spring MVC project in the Spring tool suite(STS) to create checkboxes using form:checkbox and form:checkboxes tags. 'spring-form.tld' tag library In Spring Framework, we can use Java Server Pages
6 min read
Spring - MVC Form Radio Button
Here, we will learn about the Spring MVC radiobutton and radiobuttons tags. We will create a basic Spring MVC project in the Spring tool suite(STS) to create radiobuttons using form:radiobutton and form:radiobuttons tags. 'spring-form.tld' tag libraryIn Spring Framework, we can use Java Server Pages
8 min read
Spring - MVC Form Drop-Down List
In this article, we will learn about the Spring MVC Dropdown list. We will create a basic Spring MVC project in Spring tool suite(STS) to make a dropdown list using form:select tag. spring-form.tld We can use Java Server Pages (JSPs) as a view component in Spring Framework. To help you implement vie
7 min read
Spring - MVC TextArea
Here we will be learning about the Spring MVC TextArea form tag. We will create a basic Spring MVC project in the Spring tool suite(STS) to get some data from the user using the TextArea form tag. spring-form.tld We can use Java Server Pages (JSPs) as a view component in Spring Framework. To help y
7 min read
Spring - MVC Hidden Field
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. In this
6 min read
Spring - MVC Regular Expression Validation
Regular Expression Validation in Spring MVC can be achieved by using Hibernate Validator which is the implementation of Bean Validation API. Hibernate Validator provides @Pattern annotation which is used for regular expression validation. Syntax: @Pattern(regex="", flag="", message="") private Strin
4 min read
Spring - MVC Password
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. In this
8 min read