Open In App

Spring – MVC 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.

Configuration

To use Spring’s form tags in our web application, we need to include the below directive at the top of the JSP page. This form tag library comes bundled in spring-webmvc.jar and the library descriptor is called spring-form.tld.

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
    -- form is the tag name prefix that is used for the tags from this library.

Spring tag Library

1) The ‘form‘ tag:

  • The ‘form‘ tag renders an HTML ‘form‘ tag.
  • It exposes a binding path to inner tags for binding the data entered.
  • It puts the command object in the PageContext so that the command object can be accessed by all the inner tags.
  • All the other tags in the spring tag library are nested tags of this form tag.

Below is an example of the form tag:

HTML




<form:form action="submit" method="post" modelAttribute="welcome">


This spring form’s form tag will generate the standard HTML form tag while processing like below,

HTML




<form id="welcome" action="submit" method="post">


2) The ‘input‘ tag:

  • The ‘input‘ tag renders an HTML ‘input‘ tag using the bound value.
  • It specifies an input field where the user can enter data.
  • This can be used with a different types of data based on the type attribute. By default value for the type attribute is ‘text‘.
  • From Spring 3.1 version, we can use other types also such as HTML5-specific types – ‘email‘, ‘month‘, ‘tel‘, ‘date‘ etc.

Below is the example of the input tag:

HTML




<form:input path="name" />


This spring form’s input tag will generate the standard HTML input tag while processing like below,

HTML




<input id="name" name="name" type="text" value=""/>


3) The ‘label‘ tag:

  • The ‘label‘ tag renders an HTML ‘label‘ tag.
  • It specifies the name/label for different types of elements that display on the UI screen.

Below is an example of the label tag:

HTML




<form:label path="name">Full Name: </form:label>


This spring form’s label tag will generate the standard HTML label tag while processing like below,

HTML




<label for="name">Full Name: </label>


4) The ‘password’ tag:

  • The ‘password‘ tag renders an HTML ‘input‘ tag with type ‘password‘ using the bound value.
  • The password tag can be used in forms involving sensitive information.
  • By default, the password entered by the user will not be shown, if we want to show the value, then we can set ‘showPassword‘ attribute to true.

Below is an example of the password tag:

HTML




<form:password path="password" />


This spring form’s password tag will generate the standard HTML password tag while processing like below,

HTML




<input id="password" name="password" type="password" value=""/>


5) The ‘checkbox’ tag:

  • The ‘checkbox‘ tag renders an HTML ‘input‘ tag with type ‘checkbox‘.
  • The checkbox tag can be used to let a user select one or more options from the limited number of choices.

Below is the example of the checkbox tag:

HTML




<form:checkbox path="job" value="Yes" />


This spring form’s checkbox tag will generate the standard HTML checkbox tag while processing like below,

HTML




<input id="job1" name="job" type="checkbox" value="Yes"/>
    <input type="hidden" name="_job" value="on"/>


  • We can see the additional hidden field after the checkbox. When a checkbox in an HTML page is not checked, its value will not be sent to the server as part of the HTTP request parameters once the form is submitted, as a workaround for this quirk, the checkbox tag follows the existing Spring convention of including a hidden parameter prefixed by an underscore (“_”) for each checkbox.

6) The ‘checkboxes’ tag:

  • The ‘checkboxes‘ tag renders multiple HTML ‘input‘ tags with type ‘checkbox‘.
  • This can be used to have a list of all the possible options for the checkbox available and pass to it at runtime in the JSP.
  • We can pass the values in an Array, a List, or a Map containing the available options in the “items” property.
  • While using a Map, the map entry key will be used as the value and the map entry’s value will be used as the label to be displayed.
  • We can also use a custom object to provide the property names for the value using “itemValue” and the label using “itemLabel“.
  • Typically the bound property is a collection so that it can hold multiple values selected by the user.

Below is the example of the checkboxes tag:

HTML




<form:checkboxes path="skill" items="${programmingSkills}" />


This spring form’s checkboxes tag will generate the standard HTML checkboxes tag while processing like below,

HTML




<span><input id="skill1" name="skill" type="checkbox" value="Java"/><label for="skill1">Java</label></span>
<span><input id="skill2" name="skill" type="checkbox" value="C++"/><label for="skill2">C++</label></span>
    <input type="hidden" name="_skill" value="on"/>


The values for the checkbox are available at runtime which we should specify in the controller class.

7) The ‘radiobutton’ tag:

  • The ‘radiobutton tag renders an HTML ‘input‘ tag with type ‘radio‘.
  • It involves multiple tag instances bound to the same property but with different values.
  • It allows the user to select only one option from a limited number of choices.

Below is an example of the radiobutton tag:

HTML




<form:radiobutton path="gender" value="Male" label="Male" />
<form:radiobutton path="gender" value="Female" label="Female" />


This spring form’s radiobutton tag will generate the standard HTML radiobutton tag while processing like below,

HTML




<input id="gender1" name="gender" type="radio" value="Male"/><label for="gender1">Male</label>
<input id="gender2" name="gender" type="radio" value="Female"/><label for="gender2">Female</label>


8) The ‘radiobuttons’ tag:

  • The ‘radiobuttons‘ tag renders multiple HTML ‘input‘ tags with type ‘radio‘.
  • This can be used to have a list of all the possible options for the radiobutton available and pass to it at runtime in the JSP.
  • We can pass the values in an Array, a List, or a Map containing the available options in the “items” property.
  • While using a Map, the map entry key will be used as the value and the map entry’s value will be used as the label to be displayed.
  • We can also use a custom object to provide the property names for the value using “itemValue” and the label using “itemLabel“.

Below is the example of the radiobuttons tag:

HTML




<form:radiobuttons path="years" items="${experienceYears}" />


This spring form’s radiobuttons tag will generate the standard HTML radiobuttons tag while processing like below,

HTML




<span><input id="years1" name="years" type="radio" value="1-3 Years"/><label for="years1">1-3 Years</label></span>
<span><input id="years2" name="years" type="radio" value="3-5 years"/><label for="years2">3-5 years</label></span>


The values for the radiobuttons are available at runtime which we should specify in the controller class.

9) The ‘select’ tag:

  • The ‘select‘ tag renders an HTML ‘select‘ element.
  • It supports data binding to the selected option directly or by the use of nested option and options tags.
  • It is used in the forms to create a dropdown list in the UI screen.

Below is the example of the select tag:

HTML




<form:select path="jobType" items="${jobType}">


This spring form’s select tag will generate the standard HTML select tag while processing like below,

HTML




<select id="jobType" name="jobType"><option value="Permanent">Permanent</option>
  <option value="Contract Based">Contract Based</option></select>


The values for the select tag are available at runtime which we should specify in the controller class.

10) The ‘option’ tag:

  • The ‘option‘ tag renders an HTML ‘option‘.
  • It sets the ‘selected‘ attribute as the appropriate based on the bound value.
  • It is used to define an option inside a select list.

Below is the example of option tag:

HTML




<form:option value="Intermediate"></form:option>


This spring form’s option tag will generate the standard HTML option tag while processing like below,

HTML




<option value="Intermediate">Intermediate</option>


11) The ‘options’ tag:

  • The ‘options‘ tag renders a list of HTML ‘option‘ tags.
  • It sets the ‘selected‘ attribute as the appropriate based on the bound value.
  • We can pass the values in an Array, a List, or a Map containing the available options in the “items” property.
  • While using a Map, the map entry key will be used as the value and the map entry’s value will be used as the label to be displayed.
  • We can also use a custom object to provide the property names for the value using “itemValue” and the label using “itemLabel“.

Below is an example of options tag:

HTML




<form:options items="${jobType}" />


This spring form’s options tag will generate the standard HTML options tag while processing like below,

HTML




<option value="Permanent">Permanent</option><option value="Contract Based">Contract Based</option>


The values for the jobType in options tag are available at runtime which we should specify in the controller class.

12) The ‘button’ tag:

  • The ‘button‘ tag renders an HTML ‘button‘ tag.
  • It defines the clickable button and the type of it can be specified using the ‘type’ attribute.

Below is an example of button tag:

HTML




<form:button>Submit</form:button>


This spring form’s button tag will generate the standard HTML button tag while processing like below,

HTML




<button type="submit" value="Submit">Submit</button>


13) The ‘hidden’ tag:

  • The ‘hidden‘ tag renders an HTML ‘input‘ tag with type ‘hidden‘ using the bound value.
  • To submit an unbound hidden value, we need to use the HTML input tag with type ‘hidden‘.

Below is an example of hidden tag:

HTML




<form:hidden path="jobType" />


This spring form’s hidden tag will generate the standard HTML hidden tag while processing like below,

HTML




<input name="jobType" type="hidden" value="Permanent"/>


14) The ‘errors’ tag:

  • The ‘errors‘ tag renders field errors in an HTML ‘span‘ tag.
  • It provides access to the errors created in the controller or those that were created by any validators associated with the controller.
  • It is used to display the errors caused by the business logic component in the UI screen.

Below is an example of errors tag:

HTML




<form:errors path="name" cssStyle="color:red"/>


This spring form’s errors tag will generate the standard HTML errors tag while processing like below,

HTML




<span id="name.errors" style="color:red">Please enter your name.</span>


Spring MVC Application

We will create a basic Spring MVC application form using the spring tag library like below,

Spring MVC Application Form

Spring MVC Application Form

Step by Step Implementation

The steps to create an application is as follows:

Step 1: Create a Spring MVC project in Spring Tool Suite.

Step 2: In STS, while creating the project based on the developer selection, it will download all the required maven dependencies, *.jar, lib files and it will provide an embedded server.

Step 3: Below is the final project structure of the Spring MVC project after creating *.java and *.jsp files also.

Project Structure

Project Structure

Implementation

Files to be created are as follows:

  • Welcome.java: Bean class to define the properties and getter/setter methods of the properties.
  • WelcomeController.java: Controller class to process the request and generate the output.
  • welcome.jsp: JSP file to get the input from the user from the browser.
  • summary.jsp: JSP file to display the processed output to the user.

1) welcome.jsp file:

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Welcome page</title>
</head>
<body>
  
    <h1>Welcome to GeeksforGeeks!</h1>
    <h3>Please enter your details</h3>
  
    <form:form action="submit" method="post" modelAttribute="welcome">
        <table>
            <tr>
                <td><form:label path="name">Full Name: </form:label></td>
                <td><form:input path="name" />
                <form:errors path="name" cssStyle="color:red"/></td>
            </tr>
            <tr>
                <td><form:label path="password">Set your Password: </form:label></td>
                <td><form:password path="password" />
                <form:errors path="password" cssStyle="color:red"/></td>
            </tr>
            <tr>
                <td><form:label path="email">E-Mail Address: </form:label></td>
                <td><form:input path="email" /></td>
            </tr>
            <tr>
                <td><form:label path="gender">Gender: </form:label></td>
                <td><form:radiobutton path="gender" value="Male" label="Male" />
                    <form:radiobutton path="gender" value="Female" label="Female" /></td>
            </tr>
            <tr>
                <td><form:label path="education">Highest Education: </form:label></td>
                <td><form:select path="education">
                        <form:option value="Intermediate"></form:option>
                        <form:option value="Graduation"></form:option>
                        <form:option value="Post-Graduation"></form:option>
                    </form:select></td>
            </tr>
            <tr>
                <td><form:label path="job">Looking for a job change?: </form:label></td>
                <td><form:checkbox path="job" value="Yes" /></td>
            </tr>
            <tr>
                <td><form:label path="company">Current company Name: </form:label></td>
                <td><form:input path="company" /></td>
            </tr>
  
            <tr>
                <td><form:label path="jobType">Job Type: </form:label></td>
                <td><form:select path="jobType" items="${jobType}">
                        </form:select></td>
            </tr>
            <tr>
                <td><form:label path="years">Years of experience: </form:label></td>
                <td><form:radiobuttons path="years" items="${experienceYears}"
                        delimiter="|" /></td>
            </tr>
            <tr>
                <td><form:label path="skill">Programming skills: </form:label></td>
                <td><form:checkboxes path="skill" items="${programmingSkills}" delimiter="|"/></td>
            </tr>
            <tr>
                <td><form:label path="note">Profile summary : </form:label></td>
                <td><form:textarea path="note" rows="4" cols="25"/></td>
            </tr>
            <tr>
                <td><form:button>Submit</form:button></td>
            </tr>
        </table>
    </form:form>
  
</body>
</html>


JSP file with all the spring library tags with the respective implementation.

2) Welcome.java file:

Java




package com.geek.app;
  
import javax.validation.constraints.Min;
import org.hibernate.validator.constraints.NotEmpty;
  
public class Welcome {
      
    @NotEmpty(message = "Please enter your name.")
    private String name;
    
    @Min(value= 6, message = "Minimum password length is 6 characters.")
    private String password;
    private String email;
    private String gender;
    private String education;
    private String company;
    private String job;
    private String jobType;
    private String years;
    private String skill;
    private String note;
      
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getEducation() {
        return education;
    }
    public void setEducation(String education) {
        this.education = education;
    }
    public String getCompany() {
        return company;
    }
    public void setCompany(String company) {
        this.company = company;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    public String getJobType() {
        return jobType;
    }
    public void setJobType(String jobType) {
        this.jobType = jobType;
    }
    public String getYears() {
        return years;
    }
    public void setYears(String years) {
        this.years = years;
    }
    public String getSkill() {
        return skill;
    }
    public void setSkill(String skill) {
        this.skill = skill;
    }
    public String getNote() {
        return note;
    }
    public void setNote(String note) {
        this.note = note;
    }
      
}


Java Bean class to define all the properties and getter/setter methods of those properties to get and set the values. We are using the annotations @NotEmpty and @Min which are available in org.hibernate.validator.constraints.NotEmpty and javax.validation.constraints.Min packages respectively to validate the name and password fields. To use these, we need to include below 2 dependencies in pom.xml file,

XML




<dependency>
  <groupId>javax.validation</groupId>
  <artifactId>validation-api</artifactId>
  <version>1.1.0.Final</version>
</dependency>
<dependency>
  <groupId>org.hibernate</groupId>
  <artifactId>hibernate-validator</artifactId>
  <version>5.2.4.Final</version>
</dependency>


3) WelcomeController.java file:

Java




package com.geek.app;
  
import java.util.Arrays;
import java.util.List;
  
import javax.validation.Valid;
  
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
  
@Controller
public class WelcomeController {
  
    @RequestMapping(value = "/")
    public String viewPage(Model model) {
          
        Welcome welcome = new Welcome();
        model.addAttribute("welcome", welcome);
        return "welcome";
    }
      
    @ModelAttribute("jobType")
    public List<String> jobType(){
        List<String> type = Arrays.asList("Permanent", "Contract Based");
        return type;
    }
      
    @ModelAttribute("programmingSkills")
    public List<String> programmingSkills(){
        List<String> skills = Arrays.asList("Java", "C++", "Python", "PHP", "JavaScript");
        return skills;
    }
      
    @ModelAttribute("experienceYears")
    public List<String> experienceYears(){
        List<String> years = Arrays.asList("1-3 Years", "3-5 years", "Above 5 Years");
        return years;
    }
  
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    public String submit(@Valid @ModelAttribute("welcome") Welcome welcome, BindingResult result) {
          
        if (result.hasErrors()) {
            return "welcome";
        }
        else {
            return "summary";
        }
    }
}


             

This is the controller class where it executes the methods based on the mapping of the request URLs. 

Annotations used:

  • @Controller, conveys to the container that this class is the spring controller class. To use this annotation we need to import org.springframework.stereotype.Controller package.
  • @RequestMapping, maps the request URLs to the specified method based on the value provided. To use this annotation, we need to import org.springframework.web.bind.annotation.RequestMapping package.
  • @ModelAttribute, used to bind a method parameter or method return value to the named model attribute. We need to import org.springframework.web.bind.annotation.ModelAttribute package.
  • @Valid, It marks a property, method parameter, or method return type for validation cascading. We need to import javax.validation.Valid.

4) summary.jsp file:

HTML




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Summary page</title>
</head>
<body>
  
    <h3>Details Submitted!!</h3>
  
    <table>
        <tr>
            <td>Full Name:</td>
            <td>${welcome.name}</td>
        </tr>
        <tr>
            <td>Your Password:</td>
            <td>${welcome.password}</td>
        </tr>
        <tr>
            <td>E-Mail Address:</td>
            <td>${welcome.email}</td>
        </tr>
        <tr>
            <td>Gender:</td>
            <td>${welcome.gender}</td>
        </tr>
        <tr>
            <td>Highest Education:</td>
            <td>${welcome.education}</td>
        </tr>
        <tr>
            <td>Current company Name:</td>
            <td>${welcome.company}</td>
        </tr>
        <tr>
            <td>Looking for a job change?:</td>
            <td>${welcome.job}</td>
        </tr>
        <tr>
            <td>Job Type:</td>
            <td>${welcome.jobType}</td>
        </tr>
        <tr>
            <td>Years of experience:</td>
            <td>${welcome.years}</td>
        </tr>
        <tr>
            <td>Programming skills:</td>
            <td>${welcome.skill}</td>
        </tr>
        <tr>
            <td>Profile summary :</td>
            <td>${welcome.note}</td>
        </tr>
    </table>
  
</body>
</html>


This is the output Jsp page to display the user entered values in the browser after the processing of the request.

Execution

  • After creating all the required .java and .jsp files, run the project on the server.
  • Right on the Project, Run as -> Run on Server.
  • Select the server in the localhost to run the application.
  • Open the URL: http://localhost:8080/app/ in the browser to get the below screen.
Welcome Page

Welcome Page 

  • As we are validating the fields Full Name and Password, submit the form without entering the Full Name and Password like below.
Error Details

Error Details

  • This way we will be getting the error to input the correct values.
  • Now, enter all the information and submit the form.
Input details

Input details

  • Click on Submit button to process the information.
Output

Output

All the details entered are submitted and being displayed on the UI screen. This way, we can use the Spring form tags in the Spring tag library – spring-form.tld based on our project requirement.



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