Spring MVC 5 - Sign Up Form Handling Example

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).
Before you get started, check out Spring Data JPA Tutorial and Spring MVC Tutorial

    Spring MVC Tutorials and Articles

In this example, we will use the @ModelAttribute and @RequestMapping annotations to handler the form data. So let us proceed to write a simple Spring MVC application for user signup form.

Tools and technologies used

  • Spring MVC - 5.1.0 RELEASE
  • JDK - 1.8 or later
  • Maven - 3.5.1
  • Apache Tomcat - 8.5
  • IDE - STS/Eclipse Neon.3
  • JSTL - 1.2.1
  • JSP - 2.3.1
Follow below 11 development steps to develop complete end-to-end Spring MVC form handling application.

Development Steps

  1. Create Maven Web Application
  2. Add Dependencies - pom.xml File
  3. Project Structure
  4. Spring Configuration - MVCConfig.java
  5. Servlet Container Initialization - SpringMvcDispatcherServletInitializer.java
  6. Model Class - SignUpForm.java
  7. Controller Class - SignUpController.java
  8. Views - signup-form.jsp and signup-success.jsp
  9. Serve Static Resources - CSS and JS
  10. Build and Run an application
  11. Demo

1. Create Maven Web Application

Let's create a Maven based web application either using a command line or from Eclipse IDE.
1.  Use Guide to Create Maven Web Application link to create a maven project using a command line. 
2. Use Create Maven Web Application using Eclipse IDE link to create maven web application using IDE Eclipse.
Once you created maven web application, refer below pom.xml file jar dependencies.

2. Add Dependencies - pom.xml File

Refer 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 below diagram.

3. Project Structure

Standard project structure for your reference -
As the name suggests Spring MVC, look at the above diagram we are using 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.

4. Spring Configuration - MVCConfig.java

Create an MVCConfig class and annotated 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 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;

/**
 * @author Ramesh Fadatare
 */

@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 above file.
  • The @Configuration is a class-level annotation indicating that an object is a source of bean definitions.
  • The @EnableWebMvc enables default Spring MVC configuration and provides the functionality equivalent to mvc:annotation-driven/ element in XML based configuration.
  • The @ComponentScan scans the stereotype annotations (@Controller, @Service etc...) in a package specified by basePackages attribute.

5. Servlet Container Initialization - SpringMvcDispatcherServletInitializer.java

In Spring MVC, The DispatcherServlet needs to be declared and mapped for processing all requests either using java or web.xmlconfiguration.
In a Servlet 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;

/**
 * @author Ramesh Fadatare
 */
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.

6. Model Class - SignUpForm.java

Let's create 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;
    }
}

7. Controller Class - SignUpController.java

Let's create 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
 * 
 * @author Ramesh Fadatare
 */
@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 comments are self-descriptive. So far we have created model and controller, now in the next step, we will create views.
To know about Spring form tags, check out Spring MVC JSP Form Tags Tutorial

8. Views - signup-form.jsp and signup-success.jsp

signup-form.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"%>
<%@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>

signup-success.jsp

This view is called once we will submit signup form successfully. In 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>

9. Static Resources - CSS and JS

Under the resources folder, create CSS and js folder. Place bootstrap, jquery CSS and js file in respective folders as shown in below diagram.

10. Build and Run an application

As we are using maven build tool so first, we will need to build this application using 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.

11. Demo

Once an application is up and running in tomcat server then hit this link into browser: http://localhost:8080/springmvc5-form-handling/showSignUpForm
On entering the URL, you will see the following page.
Fill the above signup form and hit submit button will navigate to signup success page as shown below:

Comments