This article is continuation of email registration, login articles, So please read the previous articles to know how to setup the project. Email is main identification in user account registration, So whenever user forgot his password, its mandatory to verify email again. Find below for flow of the program

Program Flow 

  1. User Enter Required details (Email ) and submits request to Server
  2. Email Id exists go to step 4, else go to step 3
  3. Inform the user that email is not exists , go to step 1
  4. Update user's status as "InResetPassword", create verification hash code
  5. Send Verification Link with hash code to Registered Email
  6. Get the hash code from database. Check this hash code with User submitted hash code
  7. If hash code matches go to step , else go to step 8 
  8. Increment verification attempts by 1
  9. If verification attempts equal to 20, Create New Hash Code and go to step 5, else go to END
  10. Update User Account status as "active" and show change password screen to user
  11. User Enter required details ( New Password, Confirm Password)
  12. Generate hash code for the password and update it as users's current password

HTML Code

System will take below highlighted field as input 
<form class="form-horizontal" id="formForgotPassword" data-toggle="validator" role="form">
    <input name="inputEmail" type="email" class="form-control" id="inputEmail" placeholder="Enter Email" data-error="Enter valid Email" required>
</form>

ForgotPassword Servlet Code

This servlet is responsible for taking email from user, generating hash code and sending verification link. Find below for post  method of ForgotPassword servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // take email from user input
    String inputEmail = request.getParameter("inputEmail");
    StatusPojo sp = new StatusPojo(); 
    try {
        // get user details for given email
        UserPojo up = UserDAO.selectUSERbyEmail(inputEmail); 
        if(up!=null) {
            // create verification code
            String hash = Utils.prepareRandomString(30);
            // update verification code in database 
            UserDAO.updateEmailVerificationHashForResetPassword(inputEmail, BCrypt.hashpw(hash,GlobalConstants.SALT));
            // send email to user with verification link
            MailUtil.sendResetPasswordLink(up.getUSER_ID()+"", inputEmail, hash);
            sp.setCode(0);
            sp.setMessage("We have sent reset password link to your email");
        } else {
            sp.setCode(-1);
            sp.setMessage("This email doesn't exist");
        }
    } catch (DBException | MessagingException e) {
        LOGGER.debug(e.getMessage());
        sp.setCode(-1);
        sp.setMessage(e.getMessage());
    }
    PrintWriter pw = response.getWriter();
    pw.write(Utils.toJson(sp));
    pw.flush();
    pw.close();
}

VerifyRegisteredEmailHash Servlet Code

This servlet is responsible for verification of email. Whenever user clicks on activation link, it will redirect to this servlet get method. Find below for get method code
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // get user Id and email verification code Hash code  
    Integer userId = Integer.parseInt(request.getParameter("userId"));
    String hash = BCrypt.hashpw(request.getParameter("hash"), GlobalConstants.SALT);
    String scope = request.getParameter("scope");
    String message = null;
    try {
        // verify with database
        if(UserDAO.verifyEmailHash(userId.toString(), hash) && scope.equals(GlobalConstants.RESET_PASSWORD)) {
           //update status as active
           UserDAO.updateStaus(userId.toString(), "active");
           //put some session for user
           request.getSession().setAttribute(GlobalConstants.USER, userId);
           request.getSession().setAttribute(GlobalConstants.IS_RESET_PASSWORD_VERIFIED, GlobalConstants.YES);
           //forward request to reset password html page
           request.getRequestDispatcher("/WEB-INF/resetPassword.html").forward(request, response);  
        } else {
           //now increment verification attempts 
           int attempts = UserDAO.incrementVerificationAttempts(userId.toString());
           if(attempts == 20) {
               // reset verification code if attempts equal to 20 
               String hashcode = Utils.prepareRandomString(30);
               UserDAO.updateEmailVerificationHash(userId.toString(), BCrypt.hashpw(hashcode, GlobalConstants.SALT));
               UserPojo up = UserDAO.selectUSER(userId.toString());
               MailUtil.sendEmailRegistrationLink(userId.toString(), up.getEMAIL(), hashcode);
               message = "20 times Wrong Email Validation Input Given. So we are sent new activation link to your Email";
           } else {
               message = "Wrong Email Validation Input";   
           }
        }
    } catch (DBException e) {
        LOGGER.debug(e.getMessage());
        message = e.getMessage();
    } catch (AddressException e) {
        message = e.getMessage();
        LOGGER.debug(e.getMessage());
    } catch (MessagingException e) {
        message = e.getMessage();
        LOGGER.debug(e.getMessage());
    }
    if(message!=null) {
        request.setAttribute(GlobalConstants.MESSAGE, message);
        request.getRequestDispatcher("/messageToUser.jsp").forward(request, response);  
    } 
}

Now Change Password  

Once email verification successfully done, user will be asked for enter new password and it will be updated to database. Find below for post method of ChangePassword servlet. This code is responsible for updating new password
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // get new password from input and hash it 
    String inputPassword = null;
    if(request.getParameter("inputPassword")!=null) {
        inputPassword = BCrypt.hashpw(request.getParameter("inputPassword"), GlobalConstants.SALT); 
    };
    
    // get user id from session
    Integer userId = (Integer) request.getSession().getAttribute(GlobalConstants.USER);
    String isResetPasswordVerified = (String) request.getSession().getAttribute(GlobalConstants.IS_RESET_PASSWORD_VERIFIED);
    StatusPojo sp = new StatusPojo();
    
    try {
        if(userId!=null && isResetPasswordVerified != null) {
            // update password if the status is in reset password or forgot password
            UserDAO.updatePassword(userId.toString(), inputPassword);
            sp.setCode(0);
            sp.setMessage("Password changed successfully");
        } else {
            sp.setCode(-1);
            sp.setMessage("Invalid input");
        }
    } catch (DBException e) {
        LOGGER.debug(e.getMessage());
        sp.setCode(-1);
        sp.setMessage(e.getMessage());
    }
    PrintWriter pw = response.getWriter();
    pw.write(Utils.toJson(sp));
    pw.flush();
    pw.close();
}

Required MySQL Queries

// to update status of user
update DEMO_USER set STATUS = ? where USER_ID = ?

// to increment email verification attempts
update DEMO_USER set EMAIL_VERIFICATION_ATTEMPTS = EMAIL_VERIFICATION_ATTEMPTS + 1 where USER_ID = ?

// to select email verification attempts
SELECT EMAIL_VERIFICATION_ATTEMPTS from DEMO_USER

// to update email verification hash code
update DEMO_USER set EMAIL_VERIFICATION_HASH = ?, EMAIL_VERIFICATION_ATTEMPTS = ? where USER_ID = ?

// to update password
update DEMO_USER set PASSWORD = ? where USER_ID = ?

50 comments:

  1. Hello, nice post but i am continuously getting an exception an exception saying "Excepion while accessing database", I have create db by seeing DAO class.Please help me out to get proper output.

    ReplyDelete
  2. i am continuously getting an exception an exception saying "Local address contains control or whitespace".

    ReplyDelete
    Replies
    1. Check whether you entered correct values in Setup.java, If you still having this issue contact me on facebook and share your project and screenshots

      Delete
  3. While sending register the new account i got this error.
    Error: 534-5.7.14 Please log in via your web browser and 534-5.7.14 then try again. 534-5.7.14 Learn more at 534 5.7.14 https://support.google.com/mail/answer/78754 ut6sm15367291pac.37 - gsmtp

    can u help me.

    ReplyDelete
    Replies
    1. are you trying to send email through gmail?. Gmail wont allow login from java mail API, Try to use other mail service

      Delete
  4. Error: 530-5.5.1 Authentication Required. Learn more at 530 5.5.1 https://support.google.com/mail/answer/14257 m1sm4971208pab.46 - gsmtp
    Now i got this error .I add the java mail api jar files and activation jar files in library.help me..

    ReplyDelete
  5. Bro please mail me video tutorial of this at bimalsajan@gmail.com pleaseeeeeeeeeee

    ReplyDelete
  6. Business management application or software has risen to importance in recent years as a procedure of improving output the in the place of work or simply evaluating with an outlook to recognizing ways enhances it in the upcoming days. In this post, we will look over the main areas that business management software can help a business in moving further and becoming as competent as probable.
    visit site

    ReplyDelete
  7. Hello, nice post but i am continuously getting an exception an exception saying "Excepion while accessing database", I have create db by seeing DAO class.Please help me out to get proper output.

    DEBUG 2016-11-16 14:27:34,217 [http-bio-8080-exec-3] com.sl.dao.UserDAO - Field 'EMAIL_VERIFICATION_ATTEMPTS' doesn't have a default value
    DEBUG 2016-11-16 14:27:34,220 [http-bio-8080-exec-3] com.sl.emailRegistration.RegisterEmail - Excepion while accessing database

    ReplyDelete
    Replies
    1. This looks like db mismatch. Try to change queries in UserDAO.java to make it work

      Delete
  8. Couldn't connect to host, port: smtp password here, 587; timeout -1

    this type of error occure

    ReplyDelete
    Replies
    1. Looks like its unable to send emails. Check your mail server configuration

      Delete
  9. problem to stare data in db ,when we store data in DB as password , in table show hash code how we can solve this problem

    ReplyDelete
  10. If you are using unix and getting this error Excepion while accessing database Tomcat logs[DEBUG 2017-07-16 21:40:51,582 [http-nio-8181-exec-2] com.sl.dao.UserDAO - Table 'demos.DEMO_USER' doesn't exist], then the database engine is case sensitive..

    ReplyDelete
  11. Hi, excellent post. Which are the libraries that you use in the project ...

    ReplyDelete
  12. Can you share database & tables.
    Can you share jar files name

    ReplyDelete
  13. Thus, it allows you to create a database solution that runs on all the major platforms including UNIX, Windows and Linux.https://www.dbdesigner.net

    ReplyDelete
  14. I want you to thank for your time of this wonderful read!!! I definately enjoy every little bit of it and I have you bookmarked to check out new stuff of your blog a must read blog! Digitogy

    ReplyDelete
  15. It's the best time to make some plans for the future and it's time to be happy. I have read this post and if I could I wish to suggest you few interesting things or advice. Perhaps you could write next articles referring to this article. I wish to read more things about it! I thought about this: The A - Z Of Encryption Software & 7 Ways To How To Encrypt A Password For Free In 60 Minutes.

    ReplyDelete
  16. your article is very good and very helpful. every one can use and know that how Creating Custom Animations for Use in Tableau. if you want to gif covert to image than check it you can easily understand that how to Use GIF Converter to Get Images for Marketing

    ReplyDelete
  17. You guys are writing some Amazing tips. Thanks for sharing this. Totally Awesome Post Please Keep Posting Regularly.
    echobeat earbuds review, chargeboost reviews, liporing review , doc socks, livewave antenna review

    ReplyDelete
  18. Thanks for sharing an article like this. The information which you have provided is better than another blog.
    sonic x pro review

    ReplyDelete
  19. Amazing post! I appreciate your hard work. Thank you for sharing. I have also share some use full information.
    Drone pro review
    PhotoStick Mobile Review
    mosquitron reviews
    eco beat earphones review

    ReplyDelete
  20. Nice Post, thanks for sharing such type of valuable content. Boobuddy Review 2020

    ReplyDelete
  21. amazing post thanks for sharing valuble content such a good information provide us.
    Live TempPro Reviews

    ReplyDelete
  22. Great piece of content after reading all this I'm feeling so overwhleming that I've gain some sort of knowledge from this page. Keep up the good work!! Thank YOU!
    Hearing Hero Reviews

    ReplyDelete
  23. Writing on any topic is quite difficult thing, how are you expressing the feeling and research in words, that's matters. You did a fablous job I really like your post. I have also write some review about electronics gadget I hope peoples will like it, and it also help them to choice right product according to their uses.
    The Photostick Review
    Correct Back Posture Review
    Starscope Monocular Review
    PrintX Pro Review 2021

    ReplyDelete
  24. Whatever you have written Glad I'm stumbled upon to this blog, the content is very information thanks for sharing such piece of knowledge with us.
    Printx Pro Review

    ReplyDelete
  25. This is a very good article particularly to those new to the blogosphere. Short but very precise info… Thanks for sharing this one. A must read post
    visit my website.... Naked

    ReplyDelete
  26. Thanks for sharing this informative blog with us. Find out the best Water Treatment Equipment & Supplies in UAE on Etisalat yellowpages.

    ReplyDelete
  27. Thanks for sharing this informative blog with us. Find out the best Weighing Scales & Measuring Tapes in UAE on Etisalat yellowpages.

    ReplyDelete
  28. Thanks for sharing informative content…Find best digital marketing company to know more and Contact us on given no.…

    ReplyDelete
  29. Nice Post Please Keep Posting Like This. I am really happy that you guys are writing content like this.

    Okinawa Flat Belly Tonic

    BioFit Probiotic

    ReplyDelete
  30. The content on your website is amazing. Thank you for sharing this time. 789betting เข้าสู่ระบบ

    ReplyDelete
  31. The 200 hour yoga teacher training in Rishikesh India is also known as an intense yoga course that focuses on Hatha and Ashtanga yoga methods. The ytt course is geared for beginning and intermediate yoga practitioners. https://niroyayogaclasses.com/200-hour-ytt-risikesh-india/

    ReplyDelete
  32. Thanks for sharing informative content.. find best forgot password content for this blog. Also visit my website pakkaoffer.com
    dominos coupons
    ola coupons
    grofers coupons
    oyo coupons
    swiggy coupons
    zomato coupons
    yatra coupons
    1mg coupons
    bigbasket coupons

    ReplyDelete
  33. Thank you for sharing this information with us.

    Java Burn Reviews

    ReplyDelete
  34. With a focus on achieving high search engine rankings with Forex planner , we offer services like search engine optimization, search engine marketing, and pay-per-click management.

    ReplyDelete
  35. Do you believe in long term investement . One of the option of doing investement is by investing in Crypto currencies. You can invest in Fudxcoin company that deals in the selling and purchasing of Crypto Currency. It is a reliable company. One need not doubt in investing in it as i have also bought crypto currency from it and feeling very satisfied with their services.
    crypto currency blockchain technology

    ReplyDelete
  36. This is an excellent article. Especially the closing section, this information is quite useful. Such information is very important to me. I'd been looking for this particular piece of information for a long time. Thank you for your time and consideration, and best wishes.
    immitation jewelry wholesale in india

    ReplyDelete
  37. Does anyone one wants to enjoy the delcious food? that to from their favourite resturants. Here comes a company that is offering a wide variety of services like home food delivery, medicine delivery,grocery products and dairy products at the customers doorsteps. It is just a matter of a click, on their app (fudx app) and in no time, you will get your ordered products at your doorsteps.
    food delivery medicine delivery dairy products grocery items

    ReplyDelete
  38. Dr. Namita Nadar is the Best Dietitian and Nutritionist in Noida and Delhi NCR. She has established her Weight Loss Centre almost two decades ago with the mission of increasing awareness about having a good diet plan or diet chart in our daily life that could bring remarkable effects on our health and lifestyle. Best Dietitian and nutritionist in Noida NCRShe cures her patient with her holistic approach consisting of proper diet planning for weight loss and weight gain, body composition analysis along with the patient’s medical condition.

    Hi

    ReplyDelete
  39. Operating from New Delhi, Delhi, India, BK IDNSUTRIES came into existence in the year 1963. We are known in the national and international market as a trustworthy manufacturer and we deal in all type of single & double facers corrugated rollers and industrial gears. Our speciality is Best UV Shaped Corrugating Rolls. Our products can meet the demand of different clients with a large quantity of models and complete specifications.

    ReplyDelete
  40. Dietitian Shivi Srivastava at Ultimate Diet Clinic helps you to lose weight & stay slim healthy with the help of nutrition diet programs or with the diet charts which she provides. Dietitians (Dietician) Shivi is trained and Nutritionists who help you to get your body in good shape and healthy with is the effect of diet plans which suites to your body.
    At Ultimate Diet Clinic, Greater Noida, We Understand the food requirment/habit and accordingly based on taste we create customized diet plan. We Alaways create diet plan based one one on one discussion so that we can provide the best suitable plan as per your body requirment because everybody metabolism different from another.because of "Every individual having different result

    ReplyDelete
  41. Great article! I found your insights incredibly valuable. It reminded me of a related post on our blog that dives deeper into this topic here Iubenda Review

    ReplyDelete

Blogroll

Popular Posts