How to Send Email After Registration with Activation Link in Java - onlyxcodes

Tuesday 11 August 2020

How to Send Email After Registration with Activation Link in Java

Welcome back friends, In this tutorial, you'll learn How to Send Email After Registration with Activation Link in Java. I've already written a blog post about building a full user registration and login system using the Java MVC architecture JSP, Servlet and MySQL base but I didn't provide email verification.


In this tutorial, I implement email confirmation functionality for freshly registered users by clicking on the activation link from the mailbox to verify their email Id. You can see the almost live web application needs you to always verify the email ids when you register. It is a very important new user who can not access our login system. Using this tactic we significantly reduce the number of spam accounts.


In this example, we'll use the JavaMail API which provides all the classes needed to send an email. The JavaMail API is a platform, protocol-independent framework which encapsulates important packages such as javax.mail and javax.mail.internet. These packages give classes for sending and receiving sample e-mails.


Let’s achieve Java Send Email feature.


How to Send Email After Registration with Activation Link in Java

Needed Tools

Java 8 – I have use version JDK 8.


XAMPP Server – In this server, I build a new database and table.


Eclipse – In this editor, I develop this project.


Jar Files – Underneath some necessary Jar files, these files help to build this project entirely.


servlet-api.jar: This jar file includes Servlet API Specification interfaces and classes. And that only includes the Servlet Specification interface (the API), we can use this to build our web application.


mysql-connector-java-5.1.15.jar: Help this jar file connect to MySQL database.


javax-mail-1.6.1.jar: Implementation of JavaMail references, including the protocol providers SMTP, IMAP, and POP3.


javax-mail-api-1.6.2.jar: Only the definition of JavaMailAPI, suitable for compiling against.


commons-codec.jar: This jar file generates text encryption, using this we generate a new member encrypted password.


activation-1.1.1.jar: The JavaBeans(TM) Activation Framework is used by the JavaMail(TM) API to manage MIME data ( note take from maven repository )


jsp-api.jar: This jar file is optional but I did include it because there was no other error.


All JAR files properly included inside the WEB-INF folder in the lib folder. See below for the full structure of the project directory.


structure of the project directory | how to send email in java

See all of the packages which I created below. We store servlet files and Java class files in these packages. 


com.onlyxcodes.config: In this package, I set up the configuration class file for the database.


com.onlyxcodes.controller: this package contains Servlet files.


com.onlyxcodes.bean: It comprises the POJO (Plain Old Java Object) class. This class protects the entity member variable by the usage of the getters and setters method.


com.onlyxcodes.dao: It includes class DAO (Data Access Object) logic for database operation. 


com.onlyxcodes.sendmail: This package contains the class file for sending mail.


com.onlyxcodes.activate: It contains the activate class file to verify new members' accounts.


Database And Table

First, you have to build a database and table where you can collect the new members' records. Below SQL codes paste your PhpMyAdmin.


CREATE TABLE IF NOT EXISTS `tbl_user` (
  `user_id` int(11) NOT NULL,
  `user_firstname` varchar(20) NOT NULL,
  `user_lastname` varchar(20) NOT NULL,
  `user_email` varchar(100) NOT NULL,
  `user_password` varchar(255) NOT NULL,
  `hash_password` varchar(255) NOT NULL,
  `status` tinyint(1) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

user table all fields structure

Dbconfig.java

I built a class file for the configuration of databases within com.onlyxcodes.config package. Within this file, we establish a connection to the MySQL database.


package com.onlyxcodes.config;

import java.sql.Connection;
import java.sql.DriverManager;

public class Dbconfig {
	
	static String dburl="jdbc:mysql://localhost:3306/email_verify_in_java_db";
	static String dbusername="root";
	static String dbpassword="";
	
	static Connection con;
	
	public static Connection getConnection() {
		
		try {
			
			Class.forName("com.mysql.jdbc.Driver");
			con=DriverManager.getConnection(dburl,dbusername,dbpassword);
		}
		catch(Exception e){
			System.out.println("Dbconfig File Error"+  e);
		}
		
		return con;
	}
	
}

registration.jsp

Make registration or sign up page, the form includes basic fields inside this page which are first name, last name, email, and passwords.


method="post" to send form data to the server as an HTTP POST request. 


When the user clicks the Register button, the RegisterServlet itself was executed according to action="RegisterServlet". It specifies the relative URL of the Servlet file responsible for managing the posted data from this form.


If any mistake occurs during the process of registration this page displays the appropriate message. Friends I avoid designing and validating code that places only the codes in the main.


<form method="post" action="RegisterServlet" id="registerForm" class="form-horizontal">
					
    <div class="form-group">
    <label class="col-sm-3 control-label">Firstname</label>
    <div class="col-sm-6">
    <input type="text" name="txt_firstname" class="form-control" placeholder="enter firstname" />
    </div>
    </div>
                    
    <div class="form-group">
    <label class="col-sm-3 control-label">Lastname</label>
    <div class="col-sm-6">
    <input type="text" name="txt_lastname" class="form-control" placeholder="enter lastname" />
    </div>
    </div>
                    
    <div class="form-group">
    <label class="col-sm-3 control-label">Email</label>
    <div class="col-sm-6">
    <input type="text" name="txt_email" class="form-control" placeholder="enter email" />
    </div>
    </div>
			
    <div class="form-group">
    <label class="col-sm-3 control-label">Password</label>
    <div class="col-sm-6">
    <input type="password" name="txt_password" class="form-control" placeholder="enter passowrd" />
    </div>
    </div>
					
    <div class="form-group">
    <div class="col-sm-offset-3 col-sm-9 m-t-15">
    <input type="submit" name="btn_register" class="btn btn-primary" value="Register">
    </div>
    </div>
			
	<div class="form-group">
    <div class="col-sm-offset-3 col-sm-9 m-t-15">
    You have a account login here? <a href="index.jsp"><p class="text-info">Login Account</p></a>		
    </div>
    </div>
				
</form>

sample registration page | how to send email in java

RegisterServlet.java

From inside package com.onlyxcodes.controller creates RegisterServlet class which is mapped to the URL: RegisterServlet by annotation @WebServlet. The annotation indicates the URL of the servlet before class.


This class interacts with two model classes between the RegisterBean and RegisterDao. The class RegisterBean binds the registration form value of the field which is defined by its object. And RegisterDao class includes logic for inserting codes to effectively create new member data into the table.


If a new member registers properly then this class sends a custom verification message to verify.jsp page. If any failure causes it will send the correct message to the registration page.


package com.onlyxcodes.controller;

import java.io.IOException;
import java.util.Random;

import javax.servlet.RequestDispatcher;
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.apache.commons.codec.digest.DigestUtils;

import com.onlyxcodes.bean.RegisterBean;
import com.onlyxcodes.dao.RegisterDao;


@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		if(request.getParameter("btn_register")!=null)
		{
			String firstname = request.getParameter("txt_firstname");
			String lastname = request.getParameter("txt_lastname");
			String email = request.getParameter("txt_email");
			String password = request.getParameter("txt_password");
			
			String newPassword = DigestUtils.md5Hex(password);
			
			String makeHash;
			Random random = new Random();
			random.nextInt(999999);
			makeHash = DigestUtils.md5Hex(""+random);
			
			RegisterBean registerBean = new RegisterBean();
			
			registerBean.setFirstname(firstname);
			registerBean.setLastname(lastname);
			registerBean.setEmail(email);
			registerBean.setPassword(newPassword);
			registerBean.setHash(makeHash);
			
			RegisterDao registerDao = new RegisterDao();
			
			String str = registerDao.RegisterUser(registerBean);
			
			if(str.equals("SUCCESS")){
                
                response.sendRedirect("verify.jsp");
            }
			else if(str.equals("sorry email already exist")){
                
                request.setAttribute("RegisterErrorMsg",str); 
                RequestDispatcher rd=request.getRequestDispatcher("registration.jsp"); 
                rd.include(request, response);
            }
            else{
                
                request.setAttribute("RegisterErrorMsg",str); 
                RequestDispatcher rd=request.getRequestDispatcher("registration.jsp"); 
                rd.include(request, response);
                response.sendRedirect("registration.jsp");
            }
		}
	
	}

}

Explanation:


Upon coding, we generate a member's encrypt / hash password. The DigestUtils.md5Hex() become from the commons-codec.jar file that I have implemented.


Using the method of Random() class we create character randomly and save it into a hash password.


String newPassword = DigestUtils.md5Hex(password);
			
String makeHash;
Random random = new Random();
random.nextInt(999999);
makeHash = DigestUtils.md5Hex(""+random);

RegisterBean.java

We build this class within com.onlyxcodes.bean package. In that class, we define registration form all properties given by the class RegisterServlet.


All properties specified by getters and setters with the public have to be private and implements.


package com.onlyxcodes.bean;

public class RegisterBean {
	
	private String firstname;
	private String lastname;
	private String email;
	private String password;
	private String hash;
	
	public String getFirstname() {
		return firstname;
	}
	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}
	public String getLastname() {
		return lastname;
	}
	public void setLastname(String lastname) {
		this.lastname = lastname;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getHash() {
		return hash;
	}
	public void setHash(String hash) {
		this.hash = hash;
	}
	
}

RegisterDao.java

This class establishes a package inside com.onlyxcodes.dao. We apply business logic within this class to test duplicate emails from the database.  If found then send an email already exists message, otherwise insert new member data into the database table.


This class communicates with the SendEmail class, and we add email sending codes to this class. 


package com.onlyxcodes.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.onlyxcodes.bean.RegisterBean;
import com.onlyxcodes.config.Dbconfig;
import com.onlyxcodes.sendmail.SendEmail;

public class RegisterDao {
	
	public String RegisterUser(RegisterBean registerBean) {
		
		String firstname = registerBean.getFirstname();
		String lastname  = registerBean.getLastname();
		String email 	 = registerBean.getEmail();
		String password  = registerBean.getPassword();
		String hash 	 = registerBean.getHash();
		
		Connection con = Dbconfig.getConnection();
		
		PreparedStatement pstmt;
		
		try
		{
			pstmt=con.prepareStatement("SELECT * FROM tbl_user WHERE user_email=? ");
			pstmt.setString(1, email);
			ResultSet rs = pstmt.executeQuery();
			
			if(rs.next())
			{
				String checkEmail = rs.getString("user_email");
				
				if(email.equals(checkEmail))
				{
					return "sorry email already exist";
				}
			}
			else
			{
				pstmt=con.prepareStatement("INSERT INTO tbl_user(user_firstname,user_lastname,"
                        + "user_email,user_password,hash_password) VALUES(?,?,?,?,?) ");
				
				pstmt.setString(1, firstname);
                pstmt.setString(2, lastname);
                pstmt.setString(3, email);
                pstmt.setString(4, password);
                pstmt.setString(5, hash);
                
                int i = pstmt.executeUpdate();
                
                if(i!=0)
                {
                	SendEmail se = new SendEmail(email, hash);
                	se.sendMail();
                	return "SUCCESS";
                }
			}
		}
		catch(Exception e)
		{
			System.out.println("RegisterDao File Error"+ e);
		}
	
		return "error";
	}

}

Fill out the form and check if the data is included in our database for testing.


insert data into table with status zero

SendEmail.java

In com.onlyxcodes.sendmail package this class creates under. Within this class, we describe two variables privately by userEmail and hsah and also by parameterized constructor implementation.


We build mail codes inside sendMail() method. Below codes is a simple move to explanation to recognize the codes easily.


package com.onlyxcodes.sendmail;

import java.util.Properties;

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;

public class SendEmail {
	
	private String userEmail;
	private String hash;
	
	public SendEmail(String userEmail, String hash) {
		super();
		this.userEmail = userEmail;
		this.hash = hash;
	}
	
	public void sendMail()
	{
		String email = ""; // sender email
		String password = ""; // sender password
		
		Properties properties = new Properties();
		
		properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");
        
        
        Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() 
        {    
            protected PasswordAuthentication getPasswordAuthentication(){
            
                return new PasswordAuthentication(email, password);
            }
        });
        
        try {
        	
        	MimeMessage message = new MimeMessage(session);
        	message.setFrom(new InternetAddress(email));
        	message.addRecipient(Message.RecipientType.TO, new InternetAddress(userEmail));
        	message.setText("Verification Link....");
            message.setText("Click Here :: "+"http://localhost:8080/Send-Email-In-Java-With-Verification/AccountActivate?key1="+userEmail+"&key2="+hash);
            Transport.send(message);
        	
        }catch(Exception e){
        	
        	System.out.println("SendEmail File Error"+ e);
        }
	}
	
}

Explanation Codes:


Defining the sender's email address and password first.


String email = ""; // sender email
String password = ""; // sender password

Create a Property class instance. We need to customize your library with the credentials of our email service provider. We will then create a Session that will be used to make our sending message. 


Specifies the IP address of the mail server. I use the Gmail server as a server of emails. I'm going to pass smtp.gmail.com as mail.smtp.host value. 


Properties properties = new Properties();
		
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");

Setup a session using our email address and password. The mail service provider gives the email and password along with the host and port parameters.


Pass Property object (properties) and Authenticator object into Session instance for authentication.


Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() 
{    
    protected PasswordAuthentication getPasswordAuthentication(){
            
        return new PasswordAuthentication(email, password);
    }
});

Build a MimeMessage instance with needed sending properties. It accepts the MIME type and headers.


The setFrom() method utilizes the email address of the sender, and addRecipient concerns the email address of the recipient member.


In setText() method set query string (account activation link). Members verify their email account by clicking on this link to activate it.


MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(email));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(userEmail));
message.setText("Verification Link....");
message.setText("Click Here :: "+"http://localhost:8080/Send-Email-In-Java-With-Verification/AccountActivate?key1="+userEmail+"&key2="+hash);

Transport class is used to send the message to receivers.


Transport.send(message);

It produces a strong URL, as you've seen, which is difficult to speculate. That is a very safe way to verify a member's email address.


send activate link to member account

verify.jsp

We'll send a sample message to the browser on this page. Members are reading this message and going to their mailbox and verifying their accounts.


I avoid designing code that places only message codes for verification.


<center>
    <h2>Thank You</h2>
    <h3>Please check your inbox and verify email</h3>
</center>

verify page | how to send email in java

AccountActivate.java

Inside com.onlyxcodes.activate the package, build this class which is mapped to the URL: AccountActivate by annotation @WebServlet. The annotation specifies the URL in front of the class. 


On their mail account, the member clicks on the account activation link, this class permanently activates account on the database.


Note:- The AccountActivate already passes in the activation link URL ( query string ).


package com.onlyxcodes.activate;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

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.onlyxcodes.config.Dbconfig;

@WebServlet("/AccountActivate")
public class AccountActivate extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String email = request.getParameter("key1");
		String hash = request.getParameter("key2");
		
		Connection con = Dbconfig.getConnection();
		
		PreparedStatement pstmt;
		
		try {
			
			pstmt=con.prepareStatement("SELECT user_email,hash_password,status FROM tbl_user WHERE user_email=? AND hash_password=? AND status='0' ");
            pstmt.setString(1, email);
            pstmt.setString(2, hash);
            ResultSet rs = pstmt.executeQuery();
            
            if(rs.next()){
                pstmt=con.prepareStatement("UPDATE tbl_user SET status='1' WHERE user_email=? AND hash_password=?");
                pstmt.setString(1, email);
                pstmt.setString(2, hash);
                int i = pstmt.executeUpdate();
                if(i==1){
                    response.sendRedirect("index.jsp");
                }
                else{
                    response.sendRedirect("registration.jsp");
                }
             }
		}
		catch(Exception e) {
			System.out.println("AccountActivate File Error"+ e);
		}
	}

}

Explanation:


The first thing we need to do is check whether we have the key1 and key2 variables in our request.getParameter. Let's allocate our local variables to make it a little easier.


String email = request.getParameter("key1");
String hash = request.getParameter("key2");

Now you use a MySQL select query to check the data from the URL against the records in our database.


get email and hash password values from URL

We used a MySQL query statement in the code below, retrieved records, and checked if the email and hash match up. But besides that, we've tested if the account status is 0.


pstmt=con.prepareStatement("SELECT user_email,hash_password,status FROM tbl_user WHERE user_email=? AND hash_password=? AND status='0' ");
pstmt.setString(1, email);
pstmt.setString(2, hash);
ResultSet rs = pstmt.executeQuery();

If records are detected then we must update the status field to 1 using an update query statement to activate the account.


If a query is executed correctly, it will be sent to the index/login page, otherwise, it will be sent to the page of registration.


if(rs.next()){
    pstmt=con.prepareStatement("UPDATE tbl_user SET status='1' WHERE user_email=? AND hash_password=?");
    pstmt.setString(1, email);
    pstmt.setString(2, hash);
    int i = pstmt.executeUpdate();
    if(i==1){
		response.sendRedirect("index.jsp");
    }
    else{
		response.sendRedirect("registration.jsp");
    }
}

See Account activate properly in the database.


activate account into the table

index.jsp

Its page is a login page that will take email and password to access the welcome page for members. When the details are incorrect, a suitable message will be shown.


method=”post” to send the form data as an HTTP POST request to the server.


Once the user clicks on the login button, the first LoginServlet happened according to action="LoginServlet". It describes the relative URL of the Servlet file responsible for handling the posted data from this form. 


<form method="post" action="LoginServlet" id="loginForm" class="form-horizontal">
					
    <div class="form-group">
    <label class="col-sm-3 control-label">Email</label>
    <div class="col-sm-6">
    <input type="text" name="txt_email" class="form-control" placeholder="enter email" />
    </div>
    </div>
			
    <div class="form-group">
    <label class="col-sm-3 control-label">Password</label>
    <div class="col-sm-6">
    <input type="password" name="txt_password" class="form-control" placeholder="enter passowrd" />
    </div>
    </div>
				
    <div class="form-group">
    <div class="col-sm-offset-3 col-sm-9 m-t-15">
    <input type="submit" name="btn_login" class="btn btn-success" value="Login">
    </div>
    </div>
				
    <div class="form-group">
    <div class="col-sm-offset-3 col-sm-9 m-t-15">
    You don't have a account register here? <a href="registration.jsp"><p class="text-info">Register Account</p></a>		
    </div>
    </div>
					
</form>

login page | how to send email in java

LoginServlet.java

Within com.onlyxcodes.controller construct class LoginServlet that is mapped to the URL: LoginServlet by annotation @WebServlet. That annotation specifies the servlet URL before the class.


This class interacts with two model classes, between LoginBean and LoginDao. The LoginBean class binds the login form value of the field which is defined by its object. LoginDao class includes business logic for users with authenticator access to the welcome page.


We create the encrypt/hash password of a member. The DigestUtils.md5Hex() become from the commons-codec.jar file that I have implemented.


If the LoginDao class returns the message "SUCCESS LOGIN" then start the session and access the welcome page for the Member. Otherwise, showing the wrong message on the login page is sufficient.


package com.onlyxcodes.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
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 javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;

import com.onlyxcodes.bean.LoginBean;
import com.onlyxcodes.dao.LoginDao;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		PrintWriter out = response.getWriter();
		
		if(request.getParameter("btn_login")!=null)
		{
			String email = request.getParameter("txt_email");
			String password = request.getParameter("txt_password");
			
			String hashPassword = DigestUtils.md5Hex(password);
			
			LoginBean loginBean = new LoginBean();
			
			loginBean.setEmail(email);
			loginBean.setPassword(password);
			loginBean.setHashPassword(hashPassword);
			
			
			LoginDao loginDao = new LoginDao();
			
			String str = loginDao.authorizeLogin(loginBean);
			
			if(str.equals("SUCCESS LOGIN"))
			{
				HttpSession session = request.getSession(true);
				session.setAttribute("user_login", loginBean.getEmail());
				RequestDispatcher rd = request.getRequestDispatcher("welcome.jsp");
				rd.forward(request, response);
			}
			else
			{
				request.setAttribute("WrongLoginMsg",str);
				RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
				rd.include(request, response);
			}
		}
	}

}

LoginBean.java

We build this class within com.onlyxcodes.bean package. In this class, we define all login form properties given by the class LoginServlet.


All properties specified by getters and setters with the public must be private and implements.


package com.onlyxcodes.bean;

public class LoginBean {
	
	private String email;
	private String password;
	private String hashPassword;
	
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getHashPassword() {
		return hashPassword;
	}
	public void setHashPassword(String hashPassword) {
		this.hashPassword = hashPassword;
	}

}

LoginDao.java

This class develops a package inside com.onlyxcodes.dao. In this class, we apply business logic to verify the approved user's email and password values from the database.


When both are found returning the message or string "SUCCESS LOGIN" to the controller, else return the message or string "WRONG EMAIL AND PASSWORD."


Note: We have written a MySQL selection query to select your email, password, and status data from our database If email and password suit. And status='1 'is important, this means that you can only log in when activating your account.


package com.onlyxcodes.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.onlyxcodes.bean.LoginBean;
import com.onlyxcodes.config.Dbconfig;

public class LoginDao {
	
	public String authorizeLogin(LoginBean loginBean)
	{
		String email = loginBean.getEmail();
		String password = loginBean.getPassword();
		String hashPassword = loginBean.getHashPassword();
		
		Connection con = Dbconfig.getConnection();
		
		PreparedStatement pstmt;
		
		try
		{
			pstmt=con.prepareStatement("SELECT * FROM tbl_user "
					+ "WHERE user_email=? AND user_password=? AND status=1");
			
			pstmt.setString(1, email);
			pstmt.setString(2, hashPassword);
			
			ResultSet rs = pstmt.executeQuery();
			
			while(rs.next())
			{
				String dbemail 	= rs.getString("user_email");
				String dbpassword = rs.getString("user_password");
				
				if(dbemail.equalsIgnoreCase(email) && dbpassword.equalsIgnoreCase(hashPassword))
				{
					return "SUCCESS LOGIN";
				}
			}
		}
		catch(Exception e) 
		{
			System.out.println("LoginDao File Error"+ e);
		}
		
		return "WRONG EMAIL AND PASSWORD";
	}

}


Programming Category (English)728x90


welcome.jsp

Users should be able to access this page properly after verifying or confirming their email. They will be able to access this page properly after a member enters correct the email and password in the login form.


Extra on this page, we check the users who do not access this page directly without session.


<h2>
    <%
    
    response.setHeader("Cache-Control", "no-cache,no-store, must-revalidate");
    response.setHeader("progma", "no-cache");
    
    session = request.getSession();
    
    if(session.getAttribute("user_login")==null || session.getAttribute("user_login")=="" || session.getAttribute("user_login").equals("")) 
    {
        response.sendRedirect("index.jsp");
    }
    %>
    
    Welcome, <%=session.getAttribute("user_login")%> 
</h2>

<h3>
    <a href="logout.jsp">Logout</a>
</h3>

</center>

Explanation :


The intention of the codes below successful logout any member not direct access to the welcome page. When they try to use these codes, no user welcome page will be shown.


response.setHeader("Cache-Control", "no-cache,no-store, must-revalidate");
response.setHeader("progma", "no-cache");

welcome page | how to send email in java

logout.jsp

If the user/member clicks on the hyperlink log out then the method session.invalidate() destroys the session and the method response.sendRedirect() sends to the login page. 


<%
if(session.getAttribute("user_login")!=null)
{
	session.removeAttribute("user_login");
	request.getSession(false);
	session.setAttribute("user_login", null);
	session.invalidate();
	response.sendRedirect("index.jsp");
}
%>

3 comments:

Post Bottom Ad