Java Spring Mvc Form Example
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"
?>
<
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
>
<
dependency
>
<
groupId
>javax.servlet</
groupId
>
<
artifactId
>javax.servlet-api</
artifactId
>
<
version
>4.0.1</
version
>
<
scope
>provided</
scope
>
</
dependency
>
<
dependency
>
<
groupId
>org.springframework</
groupId
>
<
artifactId
>spring-context</
artifactId
>
<
version
>5.3.15</
version
>
</
dependency
>
<
dependency
>
<
groupId
>javax.servlet.jsp.jstl</
groupId
>
<
artifactId
>jstl</
artifactId
>
<
version
>1.2</
version
>
</
dependency
>
<
dependency
>
<
groupId
>org.springframework</
groupId
>
<
artifactId
>spring-core</
artifactId
>
<
version
>5.3.15</
version
>
</
dependency
>
<
dependency
>
<
groupId
>org.springframework</
groupId
>
<
artifactId
>spring-web</
artifactId
>
<
version
>5.3.15</
version
>
</
dependency
>
<
dependency
>
<
groupId
>org.springframework</
groupId
>
<
artifactId
>spring-webmvc</
artifactId
>
<
version
>5.3.15</
version
>
</
dependency
>
<
dependency
>
<
groupId
>javax.servlet.jsp</
groupId
>
<
artifactId
>javax.servlet.jsp-api</
artifactId
>
<
version
>2.3.3</
version
>
<
scope
>provided</
scope
>
</
dependency
>
<
dependency
>
<
groupId
>org.springframework</
groupId
>
<
artifactId
>spring-orm</
artifactId
>
<
version
>5.3.15</
version
>
</
dependency
>
</
dependencies
>
<
build
>
<
finalName
>SpringMvcStudentForm</
finalName
>
<
pluginManagement
>
<
plugins
>
<
plugin
>
<
artifactId
>maven-clean-plugin</
artifactId
>
<
version
>3.1.0</
version
>
</
plugin
>
<
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
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"
?>
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;
public
Student() {
super
(); }
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"%>
<!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
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.
Source: https://www.geeksforgeeks.org/spring-mvc-form-handling/
0 Response to "Java Spring Mvc Form Example"
Post a Comment