Open In App

Spring MVC – Create Registration Form using Form Tag Library

Improve
Improve
Like Article
Like
Save
Share
Report

Spring Framework provides spring’s form tag library for JSP views in Spring’s Web MVC framework. In Spring Framework, we use Java Server Pages(JSP) as a view component to interact with the user. From version 2.0, Spring Framework provides a comprehensive set of data binding-aware tags. These tags are used for handling form elements when using JSP and Spring Web MVC. Each tag in the tag library provides support for the set of attributes of its corresponding HTML tag counterpart, making the tags familiar and intuitive to use. These tags renders the HTML tag that is HTML 4.01/XHTML 1.0 compliant. Spring’s form tag library is integrated with Spring Web MVC. It gives the tag access to the command object and reference data the controller deals with. The implementation of all the tags in the Spring tag library is available in org.springframework.web.servlet.tags.form package in Spring API. 

Refer to this article to read in detail: Spring MVC – Form Tag Library

So in this article, we are going to create a registration form using the Form Tag Library. We are going to use the following component to design our registration page.

A sample image is given below to get an idea about what we are going to do in this article.

 

Example Project

Setup the Project

We are going to use Spring Tool Suite 4 IDE for this project. Please refer to this article to install STS on your local machine How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE? Go to your STS IDE then create a new maven project, File > New > Maven Project, and choose the following archetype as shown in the below image as follows:  

 

Add the following maven dependencies and plugin to your pom.xml file. 

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>5.3.18</version>
</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>

<!-- plugin -->
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
</build>

Below is the complete code for the pom.xml file after adding these dependencies.

File: pom.xml 

XML




    <modelVersion>4.0.0</modelVersion>
    <groupId>com.geeksforgeeks</groupId>
    <artifactId>simple-calculator</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>simple-calculator Maven Webapp</name>
    <url>http://maven.apache.org</url>
    
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.18</version>
        </dependency>
        
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    
    <build>
        <finalName>simple-calculator</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


Configuring Dispatcher Servlet

Before moving into the coding part let’s have a look at the file structure in the below image. 

 

Note: Please refer to the green color box files. Other files are not present in this project. 

So at first create an src/main/java folder and inside this folder create a class named CalculatorAppIntilizer and put it inside the com.geeksforgeeks.calculator.config package and extends the AbstractAnnotationConfigDispatcherServletInitializer class. Refer to the below image.

 

And whenever you are extending this class, it has some pre abstract methods that we need to provide the implementation. Now inside this class, we have to just write two lines of code to Configure the Dispatcher Servlet. Before that, we have to create another class for the Spring configuration file. So, go to the src/main/java folder and inside this folder create a class named CalculatorAppConfig and put it inside the com.geeksforgeeks.calculator.config package. Below is the code for the CalculatorAppConfig.java file.

File: CalculatorAppConfig.java

Java




package com.geeksforgeeks.calculator.config;
  
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
  
@Configuration
@ComponentScan(basePackages = "com.geeksforgeeks.calculator.controllers")
public class CalculatorAppConfig {
  
}


And below is the complete code for the CalculatorAppIntilizer.java file. Comments are added inside the code to understand the code in more detail.

File: CalculatorAppIntilizer.java

Java




package com.geeksforgeeks.calculator.config;
  
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
  
public class CalculatorAppIntilizer extends AbstractAnnotationConfigDispatcherServletInitializer {
  
    @Override
    protected Class<?>[] getRootConfigClasses() {
        // TODO Auto-generated method stub
        return null;
    }
  
    // Registering the Spring config file
    @Override
    protected Class<?>[] getServletConfigClasses() {
        Class aClass[] = { CalculatorAppConfig.class };
        return aClass;
    }
  
    // Add mapping url
    @Override
    protected String[] getServletMappings() {
        String arr[] = { "/geeksforgeeks.org/*" };
        return arr;
    }
  
}


Setup ViewResolver

Spring MVC is a Web MVC Framework for building web applications. In generic all MVC frameworks provide a way of working with views. Spring does that via the ViewResolvers, which enables you to render models in the browser without tying the implementation to specific view technology. Read more here: ViewResolver in Spring MVC. So for setting up ViewResolver go to the CalculatorAppConfig.java file and write down the code as follows

@Bean
public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }

And below is the updated code for the CalculatorAppConfig.java file after writing the code for setting up the ViewResolver. 

File: Updated CalculatorAppConfig.java

Java




package com.geeksforgeeks.calculator.config;
  
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
  
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.geeksforgeeks.calculator.controllers")
public class CalculatorAppConfig {
  
    // setup ViewResolver
    @Bean
    public InternalResourceViewResolver viewResolver() {
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/view/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
  
}


Create DTO

At first, we have to create a DTO class. So go to the src/main/java folder and inside this folder create a class named UserRegistrationDTO and put it inside the com.geeksforgeeks.calculator.dto package. Below is the code for the UserRegistrationDTO.java file. Comments are added inside the code to understand the code in more detail.

File: UserRegistrationDTO.java

Java




package com.geeksforgeeks.calculator.dto;
  
public class UserRegistrationDTO {
  
    private String name;
    private String userName;
    private char[] password;
    private String branch;
    private String skills;
    private String gender;
  
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
  
    public String getUserName() {
        return userName;
    }
  
    public void setUserName(String userName) {
        this.userName = userName;
    }
  
    public char[] getPassword() {
        return password;
    }
  
    public void setPassword(char[] password) {
        this.password = password;
    }
  
    public String getBranch() {
        return branch;
    }
  
    public void setBranch(String branch) {
        this.branch = branch;
    }
  
    public String getSkills() {
        return skills;
    }
  
    public void setSkills(String skills) {
        this.skills = skills;
    }
  
    public String getGender() {
        return gender;
    }
  
    public void setGender(String gender) {
        this.gender = gender;
    }
  
}


Create Controller 

Go to the src/main/java folder and inside this folder create a class named RegistrationController and put it inside the com.geeksforgeeks.calculator.controllers package. Below is the code for the RegistrationController.java file.

File: RegistrationController.java file

Java




package com.geeksforgeeks.calculator.controllers;
  
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
  
import com.geeksforgeeks.calculator.dto.UserRegistrationDTO;
  
@Controller
public class RegistrationController {
      
    @RequestMapping("/register")
    public String showRegistrationPage(@ModelAttribute("userRegInfo") UserRegistrationDTO userRegistrationDTO) {
        return "registration-page";
    }
      
}


Reference article: Spring MVC @ModelAttribute Annotation with Example  

Create View

Now we have to create a view named “registration-page” inside the WEB-INF/view folder with the .jsp extension. So go to the src > main > webapp > WEB-INF and create a folder view and inside that folder create a jsp file named registration-page. So below is the code for the registration-page.jsp file. Comments are added inside the code to understand the code in more detail.

File: registration-page.jsp

HTML




<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
  
<html>
<body>
  
    <h1 align="center">Create Registration Form using Form Tag in Spring MVC</h1>
          
    <form:form modelAttribute="userRegInfo"
      
    <div align="center">
      
    <!-- A Simple Input Field -->
    <label>Name : </label>
    <form:input path="name"/>
      
    <br/>
      
    <label>User Name : </label>
    <form:input path="userName"/>
      
    <br/>
      
    <label>Password : </label>
    <form:password path="password"/>
      
    <br/>
      
    <!-- DropDown Field -->
    <label>Branch : </label>
    <form:select path="branch">
        <form:option value="CSE" label="Computer Science"></form:option>
        <form:option value="CSA" label="Computer Science and Application"></form:option>
        <form:option value="EE" label="Electrical Engineering"></form:option>
        <form:option value="ME" label="Mechanical Engineering"></form:option>
    </form:select>
      
    <br/>
      
    <!-- CheckBox Field -->
    <label>Skills : </label>
    Java : <form:checkbox path="skills" value="java"/>
    Python : <form:checkbox path="skills" value="python"/>
    C++ : <form:checkbox path="skills" value="cpp"/>
    DSA : <form:checkbox path="skills" value="dsa"/>
    Spring : <form:checkbox path="skills" value="spring"/>
      
    <br/>
      
    <!-- RadioButton Field -->
    <label>Gender : </label>
    Male<form:radiobutton path="gender" value="male"/>
    Female<form:radiobutton path="gender" value="female"/>
      
    <br/>
      
    <!-- Button Field -->
    <input type="submit" value="Register">
      
    </div>
      
    </form:form>
  
</body>
</html>


So now we have done with the coding part. Let’s run and test our application. 

Run Your Application

To run our Spring MVC Application right-click on your project > Run As > Run on Server. And run your application as shown in the below image as depicted below as follows:  

 

After that use the following URL to run your controller

http://localhost:8080/simple-calculator/geeksforgeeks.org/register

Output:

 

So we have successfully created a registration page using Form Tag. In the next article, we are going to see How to Capture and Display these Data on our web page



Last Updated : 22 May, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads