Last Updated on 04 July 2019   |   Print Email
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.
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: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:
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: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);
}
}
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_passwordfor 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:
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:
On the login form, click “I forgot password” to see the reset password form:Enter the customer’s email and click Send me new password, a successful message gets displayed like this:The customer checks his email would see the following email message:That’s how to implement the forgot password feature for an existing Java web application with Servlet, JSP and JavaMail.
Nam Ha Minh 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.
Comments
Please sir i am new to JAVA, could you help me with a template?
I suppose that it's your own class.