In this Java tutorial, you will learn how to write code to implement the forgot password feature for an existing Java web application which is built using Java Servlet and JSP. Suppose that your application has the customer login feature, and now you want to add the forgot password feature that allows the customers to get a new password in case they forgot theirs.

Customer Login Form

 

1. The solution to implement forgot password feature

There can be different solutions, and here we go for a simple, typical one: reset the customer’s password to a random string and then send the new password to the customer’s email. The following activity diagram explains the process:

forgot password activity diagram

This method is fairly secure, as only the customer can access his email to know the new password.


2. Specify additional dependencies for the project

Since the application needs to send new password to the customer via email, we need to specify the dependency of JavaMail in the project’s pom.xml file as follows:

<dependency>
	<groupId>com.sun.mail</groupId>
	<artifactId>javax.mail</artifactId>
	<version>1.6.0</version>
</dependency>

And to generate a random password string, we use the Apache Commons Lang library:

<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-lang3</artifactId>
	<version>3.8.1</version>
</dependency>


3. Code Forgot Password Form

In the login JSP page, create a hyperlink “I forgot my password” that allows the customer to reset their password:

<a href="/reset_password">I forgot my password</a>

The hyperlink points to a JSP page that displays a form that allows the customer to enter his email address. Code of this page is as follows:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
	"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	<title>Reset Password</title>
	<link rel="stylesheet" href="/css/style.css" >
	<script type="text/javascript" src="/js/jquery-3.3.1.min.js"></script>
	<script type="text/javascript" src="/js/jquery.validate.min.js"></script>
</head>
<body>
	<jsp:directive.include file="header.jsp" />
	
	<div align="center">
		<h2>Reset Your Password</h2>
		<p>
		Please enter your login email, we'll send a new random password to your inbox: 
		</p>
		
		<form id="resetForm" action="reset_password" method="post">
			<table>
				<tr>
					<td>Email:</td>
					<td><input type="text" name="email" id="email" size="20"></td>
				</tr>	
				<tr>
					<td colspan="2" align="center">
						<button type="submit">Send me new password</button>
					</td>
				</tr>		
			</table>
		</form>
	</div>
	
	<jsp:directive.include file="footer.jsp" />
	
<script type="text/javascript">

	$(document).ready(function() {
		$("#resetForm").validate({
			rules: {
				email: {
					required: true,
					email: true
				}		
			},
			
			messages: {
				email: {
					required: "Please enter email",
					email: "Please enter a valid email address"
				}
			}
		});

	});
</script>	
</body>
</html>

And here’s how the form looks like when running:

reset password form

You see, if the customer forgot password, he can use this form to get the new password. Just enter his email and click the Send me new password button.


4. Code Email Utility Class

Next, code a utility class that has a method for sending an email message:

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
 
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
/**
 * A utility class for sending e-mail messages
 * @author www.codejava.net
 *
 */
public class EmailUtility {
    public static void sendEmail(String host, String port,
            final String senderEmail, String senderName, final String password, 
            String recipientEmail, String subject, String message) throws AddressException,
            MessagingException, UnsupportedEncodingException {
 
        // sets SMTP server properties
        Properties properties = new Properties();
        properties.put("mail.smtp.host", host);
        properties.put("mail.smtp.port", port);
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
 
        // creates a new session with an authenticator
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(senderEmail, password);
            }
        };
 
        Session session = Session.getInstance(properties, auth);
 
        // creates a new e-mail message
        Message msg = new MimeMessage(session);
 
        msg.setFrom(new InternetAddress(senderEmail, senderName));
        InternetAddress[] toAddresses = { new InternetAddress(recipientEmail) };
        msg.setRecipients(Message.RecipientType.TO, toAddresses);
        msg.setSubject(subject);
        msg.setSentDate(new Date());
        msg.setText(message);
 
        // sends the e-mail
        Transport.send(msg);
 
    }
}

We will use the sendEmail() method to send an email message to the customer after resetting his password.

Learn more: Sending e-mail with JSP, Servlet and JavaMail


5. Configure SMTP settings in web.xml

To send email, a SMTP server is needed. So we need to configure SMTP settings in the web.xml file like this:

<context-param>
    <param-name>host</param-name>
    <param-value>your_stmp_server</param-value>
</context-param>

<context-param>
    <param-name>port</param-name>
    <param-value>25</param-value>
</context-param>

<context-param>
    <param-name>email</param-name>
    <param-value>your sender email</param-value>
</context-param>

<context-param>
    <param-name>name</param-name>
    <param-value>your sender name</param-value>
</context-param>
 
<context-param>
    <param-name>pass</param-name>
    <param-value>your sender email password</param-value>
</context-param>

Use values according to your SMTP server settings. If you use Gmail’s SMTP server, the settings would look like this:

<context-param>
    <param-name>host</param-name>
    <param-value>smtp.gmail.com</param-value>
</context-param>

<context-param>
    <param-name>port</param-name>
    <param-value>587</param-value>
</context-param>

<context-param>
    <param-name>email</param-name>
    <param-value>YOUR_EMAIL</param-value>
</context-param>
<context-param>
    <param-name>name</param-name>
    <param-value>YOUR_NAME</param-value>
</context-param>
<context-param>
    <param-name>pass</param-name>
    <param-value>YOUR_PASSWORD</param-value>
</context-param>

Just change your email, name and password accordingly.


6. Code Reset Password Java Servlet Class

And finally, code a Java Servlet class to handle requests for the forgot password feature. Write the code as follows:

package com.bookstore.controller.frontend;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bookstore.service.CustomerServices;

/**
 * A Java Servlet to handle requests to reset password for customer
 * 
 * @author www.codejava.net
 *
 */
@WebServlet("/reset_password")
public class ResetPasswordServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private String host;
	private String port;
	private String email;
	private String name;
	private String pass;

	public void init() {
		// reads SMTP server setting from web.xml file
		ServletContext context = getServletContext();
		host = context.getInitParameter("host");
		port = context.getInitParameter("port");
		email = context.getInitParameter("email");
		name = context.getInitParameter("name");
		pass = context.getInitParameter("pass");
	}

	public ResetPasswordServlet() {
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String page = "reset_password.jsp";
		request.getRequestDispatcher(page).forward(request, response);

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String recipient = request.getParameter("email");
		String subject = "Your Password has been reset";

		CustomerServices customerServices = new CustomerServices(request, response);
		String newPassword = customerServices.resetCustomerPassword(recipient);

		String content = "Hi, this is your new password: " + newPassword;
		content += "\nNote: for security reason, "
				+ "you must change your password after logging in.";

		String message = "";

		try {
			EmailUtility.sendEmail(host, port, email, name, pass, 
					recipient, subject, content);
			message = "Your password has been reset. Please check your e-mail.";
		} catch (Exception ex) {
			ex.printStackTrace();
			message = "There were an error: " + ex.getMessage();
		} finally {
			request.setAttribute("message", message);
			request.getRequestDispatcher("message.jsp").forward(request, response);
		}
	}

}

As you can see, this servlet handles the requests with the relative URL /reset_password for both GET and POST methods.

The init() method read values of SMTP settings from the web.xml file. The doGet() method forwards the request to the reset password JSP page, and the doPost() handles the form submission.

Suppose that you implemented the CustomerServices class with the resetCustomerPassword() method as follows:

public String resetCustomerPassword(String email) {
	Customer customer = customerDAO.findByEmail(email);
	
	String randomPassword = RandomStringUtils.randomAlphanumeric(10);
	
	customer.setPassword(randomPassword);
	customerDAO.update(customer);
	
	return randomPassword;
}

Note that it generates a random String using RandomStringUtils class from the Apache Commons Lang library. Then update the customer’s password to this new random String. The random password is also used the content of the email which is sent to the customer.

The important point here is adapting the reset password servlet class with your CustomerServices and CustomerDAO classes appropriately.

And code of the message page is fairly simple. Here’s its important code:

<div align="center">
	<br/>
	<h3>${message}</h3>
	<br/>
</div>

This is to display the successful/error message.


7. Test the Forgot Password Feature

On the login form, click “I forgot password” to see the reset password form:

reset password form

Enter the customer’s email and click Send me new password, a successful message gets displayed like this:

successful message

The customer checks his email would see the following email message:

email

That’s how to implement the forgot password feature for an existing Java web application with Servlet, JSP and JavaMail.

 

Other Java Coding Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.

Add comment

   


Comments 

#19Thuy Duong2022-01-17 11:31
Can you send me code in CustomerServices and CustomerDAO? Pls. Thanks
Quote
#18Peter Kampete2021-06-14 13:57
Quoting Nam:
Hi Peter Kampete,
I suppose that it's your own class.


Please sir i am new to JAVA, could you help me with a template?
Quote
#17Nam2021-06-11 23:11
Hi Peter Kampete,
I suppose that it's your own class.
Quote
#16Peter Kampete2021-06-11 10:08
GOOD DAY SIR. plEASE WHERE DO I GET THE CUSTOMER DAO CLASS?
Quote
#15Quang Nguyễn2021-05-20 02:44
Thanks you Bro. good lesson
Quote