In this article, we will learn how to create and submit a simple form (signup form) in Spring MVC application using Spring MVC 5+, Maven build tool, JSP, and Eclipse IDE or STS.
In this example, we will use a Java-based configuration that is we configure the Spring DispatcherServlet and spring beans configuration using all Java Code (no XML).
In this example, we will use the @ModelAttribute and @RequestMapping annotations to handle the form data. So let us proceed to write a simple Spring MVC application for the user signup form.
Follow below 11 development steps to develop a complete end-to-end Spring MVC form handling application.
Let's create a Maven-based web application either using a command line or from Eclipse IDE.
Once you created a maven web application, refer to the pom.xml file jar dependencies.
Refer to the following pom.xml file and add jar dependencies to your pom.xml.
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.javaguides.springmvc</groupId> <artifactId>springmvc5-form-handling</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springmvc5-form-handling Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <failOnMissingWebXml>false</failOnMissingWebXml> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.0.RELEASE</version> </dependency> <!-- JSTL Dependency --> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>javax.servlet.jsp.jstl-api</artifactId> <version>1.2.1</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- Servlet Dependency --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency> <!-- JSP Dependency --> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.1</version> <scope>provided</scope> </dependency> </dependencies> <build> <sourceDirectory>src/main/java</sourceDirectory> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
Note that we are using spring-webmvc dependency for a Spring MVC web application.
Next, let's create a standard project structure, please refer to the below diagram.
Standard project structure for your reference -
As the name suggests Spring MVC, look at the above diagram we are using the Model-View-Controller approach.
Model - SignUpForm.java
Views - signup-form.jsp and signup-success.jsp
Controller - SignUpController.java
Next step, we will configure Spring beans using Java-based configuration.
Create an MVCConfig class and annotated it with @Configuration, @EnableWebMvc, and @ComponentScan annotations. In this MVCConfig class, we configure the resource handler to serve the static resources (CSS, JavaScript, or Images) in the Spring MVC application.
To configure the resource handler, we need to override the default addResourceHandlers() method of WebMvcConfigurer interface in our web @Configuration class as follows.
package net.javaguides.springmvc.form.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; @Configuration @EnableWebMvc @ComponentScan(basePackages = { "net.javaguides.springmvc.form" }) public class MVCConfig implements WebMvcConfigurer { @Bean public InternalResourceViewResolver resolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setViewClass(JstlView.class); resolver.setPrefix("/WEB-INF/views/"); resolver.setSuffix(".jsp"); return resolver; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry .addResourceHandler("/resources/**") .addResourceLocations("/resources/"); } }
Let's look at few important annotations from the above file.
In Spring MVC, The DispatcherServlet needs to be declared and mapped for processing all requests either using java or web.xml configuration.
In a Ser vlet 3.0+ environment, you can use AbstractAnnotationConfigDispatcherServletInitializer class to register and initialize the DispatcherServlet programmatically as follows.
package net.javaguides.springmvc.form.config; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class SpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class << ? > [] getRootConfigClasses() { // TODO Auto-generated method stub return null; } @Override protected Class << ? > [] getServletConfigClasses() { return new Class[] { MVCConfig.class }; } @Override protected String[] getServletMappings() { return new String[] { "/" }; } }
Next step, we will create a SignUpForm class Model.
Let's create a SignUpForm Java class for binding data to the model and rendering model data on views.
package net.javaguides.springmvc.form.model; public class SignUpForm { private String firstName; private String lastName; private String email; private String userName; private String password; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
Let's create a SignUpController controller class annotated with @Controller annotation as follows:
package net.javaguides.springmvc.form.controller; 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; import net.javaguides.springmvc.form.model.SignUpForm; /** * SignUpController class for User sign up form processing */ @Controller public class SignUpController { /** * Create new signUpForm object for empty from * * @return */ @ModelAttribute("signUpForm") public SignUpForm setSignUpForm() { return new SignUpForm(); } /** * Method to show the initial HTML form * * @return */ @GetMapping("/showSignUpForm") public String showForm() { return "signup-form"; } /** * Save User sign up form * * @param signUpForm * @param model * @return */ @PostMapping("/saveSignUpForm") public String saveUser(@ModelAttribute("signUpForm") SignUpForm signUpForm, Model model) { // Implement business logic to save user details into a database // ..... System.out.println("FirstName : " + signUpForm.getFirstName()); System.out.println("LastName : " + signUpForm.getLastName()); System.out.println("Username : " + signUpForm.getUserName()); System.out.println("Password : " + signUpForm.getPassword()); System.out.println("Email : " + signUpForm.getEmail()); model.addAttribute("message", "User SignUp successfully."); model.addAttribute("user", signUpForm); return "signup-success"; } }
Please refer to comments that are self-descriptive. So far we have created a model and controller, now in the next step, we will create views.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Spring MVC 5 - form handling | Java Guides</title> <link href="<c:url value="/resources/css/bootstrap.min.css" />" rel="stylesheet"> <script src="<c:url value="/resources/js/jquery-1.11.1.min.js" />"></script> <script src="<c:url value="/resources/js/bootstrap.min.js" />"></script> </head> <body> <div class="container"> <div class="col-md-offset-2 col-md-7"> <h2 class="text-center">Spring MVC 5 Form Handling Example - Sign up Form</h2> <div class="panel panel-info"> <div class="panel-heading"> <div class="panel-title">Sign Up</div> </div> <div class="panel-body"> <form:form action="saveSignUpForm" cssClass="form-horizontal" method="post" modelAttribute="signUpForm"> <div class="form-group"> <label for="firstname" class="col-md-3 control-label">First Name</label> <div class="col-md-9"> <form:input path="firstName" cssClass="form-control" /> </div> </div> <div class="form-group"> <label for="lastname" class="col-md-3 control-label">Last Name</label> <div class="col-md-9"> <form:input path="lastName" cssClass="form-control" /> </div> </div> <div class="form-group"> <label for="icode" class="col-md-3 control-label">User Name </label> <div class="col-md-9"> <form:input path="userName" cssClass="form-control" /> </div> </div> <div class="form-group"> <label for="password" class="col-md-3 control-label">Password</label> <div class="col-md-9"> <form:password path="password" cssClass="form-control" /> </div> </div> <div class="form-group"> <label for="email" class="col-md-3 control-label">Email</label> <div class="col-md-9"> <form:input path="email" cssClass="form-control" /> </div> </div> <div class="form-group"> <!-- Button --> <div class="col-md-offset-3 col-md-9"> <form:button cssClass="btn btn-primary">Submit</form:button> </div> </div> </form:form> </div> </div> </div> </div> </body> </html>
This view is called once we will submit the signup form successfully. On this page, we will see signup form submitted data.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>javaguides.net</title> <link href="<c:url value="/resources/css/bootstrap.min.css" />" rel="stylesheet"> <script src="<c:url value="/resources/js/jquery-1.11.1.min.js" />"></script> <script src="<c:url value="/resources/js/bootstrap.min.js" />"></script> </head> <body> <div class="container"> <div class="col-md-offset-2 col-md-7"> <h1>${message}</h1> <hr /> <table class="table table-striped table-bordered"> <tr> <td><b>First Name </b>: ${user.firstName}</td> </tr> <tr> <td><b>Last Name </b> : ${user.lastName}</td> </tr> <tr> <td><b>UserName </b> : ${user.userName}</td> </tr> <tr> <td><b>Email </b>: ${user.email}</td> </tr> </table> </div> </div> </body> </html>
Under the resources folder, create the CSS and js folders. Place bootstrap, jquery CSS, and js file in respective folders as shown in the below diagram.
As we are using the maven build tool so first, we will need to build this application using the following maven command:
clean install
Once build success, then we will run this application on tomcat server 8.5 in IDE or we can also deploy war file on external tomcat webapps folder and run the application.
On entering the URL, you will see the following page.
Fill the above signup form and hit submit button will navigate to the signup success page as shown below: