Sunday, December 29, 2024
Google search engine
HomeLanguagesJavaSpring – MVC Password

Spring – MVC Password

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 Password tag. We will create a basic Spring MVC project in the Spring tool suite(STS) to take password from the user using form:password 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 ‘password’ tag

The ‘password‘ tag renders an HTML ‘input’ tag with type ‘password’ using the bound value. It defines a password field means, the characters will be masked. We can use this tag in the forms where the user has to input any type of sensitive/confidential information. Below is the example of the ‘password’ form tag.

HTML




<form:password path="password" />


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

HTML




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


Attributes in ‘password’ tag

Below are the various attributes available in the ‘password’ 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.
dir To specify text direction of elements content.
lang To specify the language of the content.
tabindex To specify tabbing order of an element.
title To specify extra information about the element on moving the cursor over the element.

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.
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.
onfocus To execute a JavaScript function when the user focuses on the text box.
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

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.
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.
readonly To set the element as read only when the value is ‘true’.
alt To specify some alternate description about 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.
showPassword To show the password field value in the screen without being masked.

Spring MVC Application

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

Spring MVC Application

Spring MVC Application

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.neveropen.app;
  
public class Home {
      
    private String name;
    private String password;
    private String email;
      
    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;
    }
      
}


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.neveropen.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 Lazyroar!!</h2>
  
    <form:form action="submit" method="post" modelAttribute="home">
        <table>
            <tr>
                <td><form:label path="name">Full Name: </form:label></td>
                <td><form:input path="name" /></td>
            </tr>
            <tr>
                <td><form:label path="password">Password: </form:label></td>
                <td><form:password path="password" maxlength="6" size="8"/></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>
  
</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>Password:</td>
            <td>${home.password}</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 all the details in the form.

Input

Input

  • As we specified the maxlength of the password field to 6 characters, we can enter 6 characters only.
  • We can specify different attributes to the password field based on our requirements.
  • For Example: If we want to change the direction of the text entered in the field based on the language used, we can use the dir attribute like below on the JSP page.

HTML




<form:password path="password" maxlength="6" size="8" dir="rtl"/>


Now, the input value direction will change like below,

Input Direction of Password field

Input Direction of Password field

Click on Submit button.

Output

Output

Once we submit the form, the entered details will be displayed on the screen

RELATED ARTICLES

Most Popular

Recent Comments