Open In App

Spring – MVC Form Tag Library

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:

Below is an example of the form tag:






<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,




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

2) The ‘input‘ tag:

Below is the example of the input tag:




<form:input path="name" />

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




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

3) The ‘label‘ tag:

Below is an example of the label tag:




<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,




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

4) The ‘password’ tag:

Below is an example of the password tag:




<form:password path="password" />

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




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

5) The ‘checkbox’ tag:

Below is the example of the checkbox tag:




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

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




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

6) The ‘checkboxes’ tag:

Below is the example of the checkboxes tag:




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

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




<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:

Below is an example of the radiobutton tag:




<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,




<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:

Below is the example of the radiobuttons tag:




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

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




<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:

Below is the example of the select tag:




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

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




<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:

Below is the example of option tag:




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

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




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

11) The ‘options’ tag:

Below is an example of options tag:




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

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




<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:

Below is an example of button tag:




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

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




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

13) The ‘hidden’ tag:

Below is an example of hidden tag:




<form:hidden path="jobType" />

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




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

14) The ‘errors’ tag:

Below is an example of errors tag:




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

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




<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

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

Implementation

Files to be created are as follows:

1) welcome.jsp file:




<%@ 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:




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,




<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:




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:

4) summary.jsp file:




<%@ 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

Welcome Page 

Error Details

Input details

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.


Article Tags :