Implement forgot password using JSP Servlet and Java mail API

In this Java web application tutorial, Let’s see how to implement forgot password feature using JSP, servlet, and Java mail API.

As we discuss in the last send Java mail tutorial. There are three main steps to send a mail using java. So let’s add some more steps and implement the forget password in Jsp and servlet.

Step 1) Create a link at the login page to redirect to forget a password.

<a href="/javawebapp/ForgetPasswordCTL" class="btn btn-link"> Forgot Your Password? </a>

Step 1) Design an HTML form to forget the password.

<%@page import="com.javawebapp.utility.ServletUtility"%>
<body>
  <%@ include file="header.jsp"%>
  <main class="login-form">
  <div class="cotainer">
    <div class="row justify-content-center">
      <div class="col-md-8">
        <div class="card">
          <div class="card-header">
            ResetPassword
            <h6 style="color: red;"><%= ServletUtility.getErrorMessage(request) %></h6>
            <h6 style="color: green;"><%= ServletUtility.getSuccessMessage(request)%></h6>
          </div>
          <div class="card-body">
            <form action="/javawebapp/ForgetPasswordCTL" method="post">
              <div class="form-group row">
                <label for="email_address" 
                  class="col-md-4 col-form-label text-md-right">Enter Email id<font color="red">*</font></label>
                <div class="col-md-6">
                  <input type="text" id="email"  class="form-control" placeholder="Enter Login Id"
                    name="email" value="" >
                    <font  color="red"></font>
                </div>
                </div>
              <div class="col-md-6 offset-md-4">
                <input type="submit" class="btn btn-primary" value="Get your password">
                
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  </div>
  </main>
  <div style="margin-top: 170px">
    <%@ include file="footer.jsp"%>
  </div>

Step 3) Add Java mail dependency in pom.xml

<dependency>
  <groupId>javax.mail</groupId>
  <artifactId>mail</artifactId>
  <version>1.4.7</version>
</dependency>

Step 4) Create a method in UserModel.java to get the password from the database.

public static UserBeans FindUserPassword(String login_id) {
    
    Connection con;
    UserBeans user = null;
    try {
      con = JDBCDataSource.getConnection();
      PreparedStatement stmt = con.prepareStatement("Select password from user where login=?");
      stmt.setString(1, login_id);
      ResultSet rs = stmt.executeQuery();
      if (rs.next()) {
        user = new UserBeans();
        
        user.setPassword(rs.getString("password"));

      }

    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return user;
    
  }

Step 4) Create a controller servlet (ForgetPasswordCTL.java).

This servlet will get the email as the user request from view(forgetpassword.jsp).  and call the method from the user method to get the user password according to the email. Set the same password in the mail and send it to the user.

package com.javawebapp.Controller;

import java.io.IOException;
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 org.omg.CORBA.portable.ApplicationException;

import com.javawebapp.beans.UserBeans;
import com.javawebapp.model.UserModel;
import com.javawebapp.utility.EmailMessage;
import com.javawebapp.utility.EmailUtility;
import com.javawebapp.utility.ServletUtility;

/**
 * Servlet implementation class ForgetPasswordCTL
 */
@WebServlet(name="ForgetPasswordCTL", urlPatterns = {"ForgetPasswordCTL"} )
public class ForgetPasswordCTL extends HttpServlet {
  private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ForgetPasswordCTL() {
        super();
        // TODO Auto-generated constructor stub
    }

  /**
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    ServletUtility.forward("/jsp/forgetpassword.jsp", request, response);
  }

  /**
   * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    String email = request.getParameter("email").trim();
    EmailMessage emailbean = new EmailMessage();
    UserBeans user = UserModel.FindUserPassword(email);
    emailbean.setTo(email);
    emailbean.setMessage("Hii "+email+ "Your Password is: "+user.getPassword());
    try {
      
      EmailUtility.sendMail(emailbean);
      ServletUtility.setSuccessMessage("Mail has been sent successfully..", request);
      
      
    } catch (ApplicationException e) {
      // TODO Auto-generated catch block
      ServletUtility.setErrorMessage("Somting Wrong", request);
    }
    ServletUtility.forward("/jsp/forgetpassword.jsp",request, response);
  }

}

EmailMessage.java

package com.javawebapp.utility;

public class EmailMessage {

  private String to = null;
  private String from = null;
  private String cc = null;
  private String bcc = null;
  private String subject = null;
  private String message = null;
  private int messageType = TEXT_MSG;
  public static final int HTML_MSG = 1;
  public static final int TEXT_MSG = 2;

  public String getTo() {
    return to;
  }

  public void setTo(String to) {
    this.to = to;
  }

  public String getFrom() {
    return from;
  }

  public void setFrom(String from) {
    this.from = from;
  }

  public String getCc() {
    return cc;
  }

  public void setCc(String cc) {
    this.cc = cc;
  }

  public String getBcc() {
    return bcc;
  }

  public void setBcc(String bcc) {
    this.bcc = bcc;
  }

  public String getSubject() {
    return subject;
  }

  public void setSubject(String subject) {
    this.subject = subject;
  }

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

  public int getMessageType() {
    return messageType;
  }

  public void setMessageType(int messageType) {
    this.messageType = messageType;
  }

}


EmailUtility.java

package com.javawebapp.utility;
import java.util.Properties;
import java.util.ResourceBundle;
 
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.omg.CORBA.portable.ApplicationException;
public class EmailUtility {
  
  private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    private static Properties props = new Properties();
   static {
       props.put("mail.smtp.host", "smtp.gmail.com");
       props.put("mail.smtp.auth", "true");
       props.put("mail.debug", "true");
       props.put("mail.smtp.port", 465);
       props.put("mail.smtp.socketFactory.port",465);
       props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
       props.put("mail.smtp.socketFactory.fallback", "false");
       props.put("mail.smtp.starttls.enable", "true");
   }

   public static void sendMail(EmailMessage emailMessageDTO) throws ApplicationException{
     String sender_Email = "vankatinull@gmail.com";
     String sender_email_pass = "Demo@123";

       try {

           // Connection to Mail Server
           Session session = Session.getDefaultInstance(props,
                   new javax.mail.Authenticator() {
                       protected PasswordAuthentication getPasswordAuthentication() {
                           return new PasswordAuthentication(sender_Email,sender_email_pass);
                       }
                   });

    
           session.setDebug(true);

           // Create a message
           Message msg = new MimeMessage(session);
           InternetAddress addressFrom = new InternetAddress(sender_Email);
           msg.setFrom(addressFrom);

           // Set TO addresses
           String[] emailIds = new String[0];

           if (emailMessageDTO.getTo() != null) {
               emailIds = emailMessageDTO.getTo().split(",");
           }

           // Set CC addresses
           String[] emailIdsCc = new String[0];

           if (emailMessageDTO.getCc() != null) {
               emailIdsCc = emailMessageDTO.getCc().split(",");
           }

           // Set BCC addresses
           String[] emailIdsBcc = new String[0];

           if (emailMessageDTO.getBcc() != null) {
               emailIdsBcc = emailMessageDTO.getBcc().split(",");
           }

           InternetAddress[] addressTo = new InternetAddress[emailIds.length];

           for (int i = 0; i < emailIds.length; i++) {
               addressTo[i] = new InternetAddress(emailIds[i]);
           }

           InternetAddress[] addressCc = new InternetAddress[emailIdsCc.length];

           for (int i = 0; i < emailIdsCc.length; i++) {
               addressCc[i] = new InternetAddress(emailIdsCc[i]);
           }

           InternetAddress[] addressBcc = new InternetAddress[emailIdsBcc.length];

           for (int i = 0; i < emailIdsBcc.length; i++) {
               addressBcc[i] = new InternetAddress(emailIdsBcc[i]);
           }

           if (addressTo.length > 0) {
               msg.setRecipients(Message.RecipientType.TO, addressTo);
           }

           if (addressCc.length > 0) {
               msg.setRecipients(Message.RecipientType.CC, addressCc);
           }

           if (addressBcc.length > 0) {
               msg.setRecipients(Message.RecipientType.BCC, addressBcc);
           }

           // Setting the Subject and Content Type
           msg.setSubject(emailMessageDTO.getSubject());

           // Set message MIME type
           switch (emailMessageDTO.getMessageType()) {
           case EmailMessage.HTML_MSG:
               msg.setContent(emailMessageDTO.getMessage(), "text/html");
               break;
           case EmailMessage.TEXT_MSG:
               msg.setContent(emailMessageDTO.getMessage(), "text/plain");
               break;

           }

           // Send the mail
           Transport.send(msg);

       } catch (Exception ex) {
           
       } 
   }


}