Spring MVC password example

In Spring MVC, you can use <form:password /> tag to render a HTML password field. For example,


<form:password path="password" />

It will renders following HTML code


<input id="password" name="password" type="password" value=""/>
Note
In Spring’s documentation, it mention about the ‘showPassword‘ attribute will display the password value, but it’s failed in my testing, may be you can try it yourself.

In this tutorial, we show you how to use Spring’s form tag “password” to render two HTML password fields – “password” and “confirmPassword”. Additionally, add a validator checks on both password fields : must not be blank, and the “password” field must match with “confirmPasswod” field.

1. Controller

A SimpleFormController to handle the form value.

File : PasswordController.java


package com.mkyong.customer.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.mkyong.customer.model.Customer;

public class PasswordController extends SimpleFormController{
	
	public PasswordController(){
		setCommandClass(Customer.class);
		setCommandName("customerForm");
	}
	
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {

		Customer customer = (Customer)command;
		return new ModelAndView("CustomerSuccess","customer",customer);
	
	}
	
}

2. Model

A Customer object to store the password value.

File : Customer.java


package com.mkyong.customer.model;

public class Customer{
	
	String password;
	String confirmPassword;
	//getter and setter methods for password and confirmPassword
}

3. Form Validator

Create a password validator class to check on the both password fields : must not be blank, “password” and “confirmPassword” must be match. Otherwise, get the corresponds message from the resource bundle (properties file).

File : PasswordValidator.java


package com.mkyong.customer.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.mkyong.customer.model.Customer;

public class PasswordValidator implements Validator{

	@Override
	public boolean supports(Class clazz) {
		//just validate the Customer instances
		return Customer.class.isAssignableFrom(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password",
			"required.password", "Field name is required.");
		
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword",
				"required.confirmPassword", "Field name is required.");
		
		Customer cust = (Customer)target;
		
		if(!(cust.getPassword().equals(cust.getConfirmPassword()))){
			errors.rejectValue("password", "notmatch.password");
		}
		
	}
	
}

File : message.properties


required.password = Password is required!
required.passwordConfirm = Confirm password is required!
notmatch.password = Password and Conform password is not match!

4. View

A JSP page to use the Spring’s form tag “password” to render two HTML password fields, and put some CSS styles to highlight the error message.

File : CustomerForm.jsp


<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<style>
.error {
	color: #ff0000;
}

.errorblock {
	color: #000;
	background-color: #ffEEEE;
	border: 3px solid #ff0000;
	padding: 8px;
	margin: 16px;
}
</style>
</head>

<body>
	<h2>Spring's form password example</h2>

	<form:form method="POST" commandName="customerForm">
		<form:errors path="*" cssClass="errorblock" element="div" />
		<table>
			<tr>
				<td>Password :</td>
				<td><form:password path="password" />
				</td>
				<td><form:errors path="password" cssClass="error" />
				</td>
			</tr>
			<tr>
				<td>Confirm Password :</td>
				<td><form:password path="confirmPassword" />
				</td>
				<td><form:errors path="confirmPassword" cssClass="error" />
				</td>
			</tr>
			<tr>
				<td colspan="3"><input type="submit" />
				</td>
			</tr>
		</table>
	</form:form>

</body>
</html>

If the form is submitted, render the successful page and display the submitted password value.

File : CustomerSuccess.jsp


<html>
<body>
	<h2>Spring's form password example</h2>

	Password : ${customer.password}
	<br /> Confirm Password : ${customer.confirmPassword}

</body>
</html>

5. Spring Bean Configuration

Link it all ~


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

  <bean
  class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />

	<bean class="com.mkyong.customer.controller.PasswordController">
		<property name="formView" value="CustomerForm" />
		<property name="successView" value="CustomerSuccess" />

		<!-- Map a validator -->
		<property name="validator">
			<bean class="com.mkyong.customer.validator.PasswordValidator" />
		</property>
	</bean>

	<!-- Register the Customer.properties -->
	<bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="message" />
	</bean>

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/pages/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>

</beans>

6. Demo

Access the page – http://localhost:8080/SpringMVCForm/password.htm

SpringMVC-Password-Example-1

If the “password” is not match the “confirmPassword” while submitting the form, display and highlight the error message.

SpringMVC-Password-Example-2

If the form is submitted successfully, just display the submitted password value.

SpringMVC-Password-Example-3

Download Source Code

Download it – SpringMVCForm-Password-Example.zip (9KB)

15 comments on “Spring MVC password example

  1. If i encrypt both password and confirm password, in the set value like:
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    String encodedPassword = passwordEncoder.encode(password);
    this.password= encodedPassword;

    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    String encodedPassword = passwordEncoder.encode(passwordConfirm);
    this.passwordConfirm= encodedPassword;

    it encrypt two different values. how can i set a same encrypt for both password and password confim?

  2. why just not use the jquery to comapre password on the client side, and keep the model clean only with one password ?

  3. if i am using annotated class and my hibernate cfg if i have to add entries like mapping class=
    In this cases should the table name and class name should match?

  4. This project also needs to add dependency for the “javax.servlet.http.HttpServlet”

    javax.servlet
    servlet-api
    2.5
    provided

  5. The Spring docs say showPassword determines whether the password value is hown or not. What that actually means is whether the rendered html tag has data in the “value” property, or whether it is rendered with value=””. In practical purposes, this affects what your form looks like if the user is returned to it due to a validation failure – it determines whether the existing password value is cleared or kept… there is some inherent risk with showPassword=true, as the cleartext password will be present in the html sent back to the browser…

  6. Stunning piece. I without a doubt clicked together with Spring MVC password example.

    I should not induce problems by just expressing this
    however, your contribution reminded me of phuket vacation packages which i read about on the online site for the purpose of password
    fairly recently.

  7. Hi,

    I downloaded this example and did :
    mvn clean install package

    I got this error :
    nnotations are not supported in -source 1.3
    (use -source 5 or higher to enable annotations)

    I googled the error and I found out adding this will fix the problem :

    maven-compiler-plugin

    1.5
    1.5

    when I added it and did : mvn clean install package

    I got :

    C:\maj\practices\spring\mkyongSpringMVC\SpringMVCForm>mvn clean install package
    [INFO] Scanning for projects…
    [INFO] ————————————————————————
    [INFO] Building SpringMVC Maven Webapp
    [INFO] task-segment: [clean, install, package]
    [INFO] ————————————————————————
    [INFO] [clean:clean {execution: default-clean}]
    [INFO] Deleting directory C:\maj\practices\spring\mkyongSpringMVC\SpringMVCForm\
    target
    [INFO] [resources:resources {execution: default-resources}]
    [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources,
    i.e. build is platform dependent!
    [INFO] Copying 1 resource
    [INFO] [compiler:compile {execution: default-compile}]
    [INFO] Compiling 3 source files to C:\maj\practices\spring\mkyongSpringMVC\Sprin
    gMVCForm\target\classes
    [INFO] ————————————————————————
    [ERROR] BUILD FAILURE
    [INFO] ————————————————————————
    [INFO] Compilation failure

    C:\maj\practices\spring\mkyongSpringMVC\SpringMVCForm\src\main\java\com\mkyong\c
    ustomer\controller\PasswordController.java:[3,25] package javax.servlet.http doe
    s not exist

    C:\maj\practices\spring\mkyongSpringMVC\SpringMVCForm\src\main\java\com\mkyong\c
    ustomer\controller\PasswordController.java:[4,25] package javax.servlet.http doe
    s not exist

    C:\maj\practices\spring\mkyongSpringMVC\SpringMVCForm\src\main\java\com\mkyong\c
    ustomer\controller\PasswordController.java:[19,33] cannot find symbol
    symbol : class HttpServletRequest
    location: class com.mkyong.customer.controller.PasswordController

    C:\maj\practices\spring\mkyongSpringMVC\SpringMVCForm\src\main\java\com\mkyong\c
    ustomer\controller\PasswordController.java:[20,3] cannot find symbol
    symbol : class HttpServletResponse
    location: class com.mkyong.customer.controller.PasswordController

    Please your help is appreciated.

Leave a Comment

Your email address will not be published. Required fields are marked *