Open In App

Spring – MVC Form Text Field

Last Updated : 20 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. In this example, we will learn about the Spring MVC form Text field. We will create a basic Spring MVC project in the Spring tool suite(STS) to take input as text from the user using form:input tag.

spring-form.tld

We can use Java Server Pages (JSPs) as a view component in Spring Framework. Spring 2.0 version provides a comprehensive set of data binding-aware tags as a tag library namely spring-form.tld for handling form elements when using JSP and Spring Web MVC.

Each tag in this 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 generate an HTML tag at the time of processing that is HTML 4.01/XHTML 1.0 compliant. We can use these tags for evaluating errors, setting themes, formatting the fields for inputting and outputting internationalized messages.

To use the spring library tags, we need to include the below directive on the JSP page.

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

The ‘input’ tag

The ‘input‘ tag renders an HTML ‘input’ tag using the bound value and type=’text‘ by default. It specifies an input field where the user can enter the data. It can be displayed in different ways based on the ‘type’ attribute such as ’email’, ‘date’ etc. Below is the example of the form ‘input’ tag.

HTML




<form:input path="name" id="name"/>


This tag will generate an HTML input tag at the time of processing like below.

HTML




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


Attributes in ‘input’ tag

Below are the various attributes available in the ‘input’ tag.

1) HTML Standard Attributes: HTML Standard attributes are also called global attributes that are available and can be used with all HTML elements.

Name

Description

accesskey To specify a shortcut key to activate/focus on an element.
id To specify a unique ID for the element.
title To specify extra information about the element on moving the cursor over the input field.
tabindex To specify tabbing order of an element.
dir To specify text direction of elements content.
lang To specify the language of the content.

2) HTML Event Attributes: HTML Event Attributes are used to trigger a function when the specified event occurred on the element.

Name

Description

onblur To execute a JavaScript function when a user leaves the text field.
onchange To execute a JavaScript function when a user changes the text.
onfocus To execute a JavaScript function when the user focuses on the text field.
onclick To execute a JavaScript function when the user clicks on the field.
ondblclick To execute a JavaScript function when the user double clicks on the element.
onkeydown To execute a JavaScript function when the user is pressing a key on the keyboard.
onkeypress To execute a JavaScript function when the user presses the key on the keyboard.
onkeyup To execute a JavaScript function when the user is releasing the key on the keyboard.
onmousedown To execute a JavaScript function when the user is pressing a mouse button.
onmousemove To execute a JavaScript function when the user is moving the mouse pointer.
onmouseout To execute a JavaScript function when the user is moving the mouse pointer out of the field.
onmouseover To execute a JavaScript function when the user is moving the mouse pointer onto the field.
onmouseup To execute a JavaScript function when the user is releasing the mouse button.
onselect To execute a JavaScript function when the user selects the text.

3) HTML Optional Attributes: HTML Optional Attributes are used to modify the default functionality of an element.

Name

Description

alt To specify some alternate description about the element.
cssClass To specify a class name for an HTML element to access it.
cssErrorClass To be used when the bounded element has errors.
cssStyle To add styles to an element, such as color, font, size etc.
readonly To set the element as read only when the value is ‘true’.
disabled To specify whether the element to be disabled or not.
size To specify the number of visible width of the element in characters.
maxlength To specify the maximum number of characters(length) allowed in the element.

4) Other Attributes:

Name

Description

autocomplete To specify the browser to display options to fill in the field, based on earlier typed values, when user starts to type in the field.
htmlEscape To enable/disable HTML escaping of rendered values.
path To specify the path to the property for binding the data.

Spring MVC Application

We will create a simple Spring MVC application like below to take the input values – First Name and Last Name, from the user and process them to get the output.

Spring MVC Form - Text field example

Spring MVC Form – Text field example

Steps to Create Application

1) Create a Spring MVC project in Spring Tool Suite.

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.

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:

  1. Home.java – Bean class – To define the field properties and getter/setter methods of the properties.
  2. HomeController.java – Controller class – To process the user request and generate the output.
  3. home.jsp – Jsp file to interact with the user for the input.
  4. summary.jsp – Jsp file to display the output after processing to the user.

1) Home.java file: Java Bean class to define all the properties and getter/setter methods of those properties to get and set the values.

Java




package com.geeksforgeeks.app;
  
public class Home {
      
    private String fName;
    private String lName;
    private String name;
    private String email;
      
      
    public String getfName() {
        return fName;
    }
    public void setfName(String fName) {
        this.fName = fName;
    }
    public String getlName() {
        return lName;
    }
    public void setlName(String lName) {
        this.lName = lName;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
      
}


2) HomeController.java file: 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.

Java




package com.geeksforgeeks.app;
  
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
  
@Controller
public class HomeController {
  
    @RequestMapping(value = "/")
    public String viewHome(Model model) {
  
        Home home = new Home();
        model.addAttribute("home", home);
        return "home";
    }
  
    @RequestMapping(value = "/submit", method = RequestMethod.POST)
    public String submit(@ModelAttribute("home") Home home) {
        return "summary";
    }
  
}


3) home.jsp file: JSP file with the spring library tags with the respective implementation.

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>
<title>Home Page</title>
</head>
<body>
    <h2>Welcome to GeeksforGeeks!!</h2>
  
    <form:form action="submit" method="post" modelAttribute="home">
        <table>
            <tr>
                <td><form:label path="fName">First Name: </form:label></td>
                <td><form:input path="fName" id="fName" maxlength="6" size="8" onblur="updateName()"/></td>
            </tr>
            <tr>
                <td><form:label path="lName">Last Name: </form:label></td>
                <td><form:input path="lName" id="lName" maxlength="10" size="10" onblur="updateName()"/></td>
            </tr>
            <tr>
                <td><form:label path="name">Full Name: </form:label></td>
                <td><form:input path="name" id="name" readonly="true" title="This is Read-only field" 
                                cssStyle="font-family:monospace;color:green"/></td>
            </tr>
            <tr>
                <td><form:label path="email">E-Mail Address: </form:label></td>
                <td><form:input path="email" /></td>
            </tr>
            <tr>
                <td><form:button>Submit</form:button></td>
            </tr>
        </table>
    </form:form>
      
    <script type="text/javascript">
          
        function updateName(){
            var firstName = document.getElementById("fName").value;
            var lastName = document.getElementById("lName").value;
              
            var fullName = firstName+" "+lastName;
            document.getElementById("name").value = fullName;
              
        }
    </script>
  
</body>
</html>


4) summary.jsp file: This is the output JSP page to display the user entered values in the browser after the processing of the request.

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>${home.name}</td>
        </tr>
        <tr>
            <td>E-Mail Address:</td>
            <td>${home.email}</td>
        </tr>
    </table>
  
</body>
</html>


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.
Home Page

Home Page

Enter the details in the respective fields.

Input

Input

  • As we specified the First Name, maxlength=”6″, we can enter up to 6 characters only in the field and for Last Name, maxlength=”10″, we can enter up to 10 characters in the Last Name field.
  • We are calling the function “updateName” on the event attribute – “onblur”, so once the value is entered into First Name and Last Name fields and when the cursor is moved out of the field, the JavaScript function will execute and it updates the Full Name field based on the values entered in First Name and Last Name fields.
  • We specified the Full Name field as, readonly=”true”, so the user cannot edit the Full Name field. Also, we gave some extra information in the title field as “title= This is Read-only field”. So, when the user moves the cursor over the text field, it displays the title value to the user as shown in the above screen.
  • We used the attribute cssStyle=”font-family:monospace;color:green”, so it displays the Full Name field by applying the specified styles to the text.
  • Click on Submit button after entering all the values.
Output

Output

Once we click on submit, the controller class will process the request and generate the output that is displayed on the screen.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads