Login Logout Example


Posted in : Servlet Posted on : November 1, 2010 at 4:56 PM Comments : [ 0 ]
Advertisements
In this tutorial you will learn how to make a login application in servlet and validate then by fetching data from database

Login Logout In Servlet

Login logout is the most common task performed in every application. It is the process of authenticate the used for the security reason. An example of login application is given below. In this example user is requesting to the servlet from HTML form. The HTML form the contains the JavaSrcipt for the validation checking of the form. The servlet gets the request parameters passed by the user and search the user name to corresponding their password. If user name equals to the database user Name (Vendor Name) then a session object is created and the name of the user is added into the session and passes to the success page otherwise user name is added to the request and passes to the failure page. To pass request from one page to another RequestDispatcher("/relativeURL") is used. This passes the request to the given URL. To get  RequestDispatcher we must have to get the ServletContext. A Simple code given below which demonstrate the Request Dispatcher.

ServletContext context=getServletContext();

RequestDispatcher dispatcher=context.getRequestDispatcher("/URL");

dispatcher.forward(request, response);

An Login Example is given below to run this example download the code unzip it and paste it to your webapps directory of your tomcat. and remember dont forget to make database as -

At first create a database of name vendor in your MySql database, and then create a table of name venderinfo as

CREATE TABLE venderinfo ( 
VendorName tinytext NOT NULL,
VendorPass varchar(50) NOT NULL,
VendorRepass varchar(50) NOT NULL
);

index.html

<HTML>
<HEAD>
<TITLE>Getting Parameter Example</TITLE>
<script type="text/javascript">

function checkform()
{ 
if (document.login.userName.value =='') {
// something is wrong
alert('Please Enter Your Name');
document.login.userName.focus();
return false;
}
else if (document.login.userPassWord.value =='')
{
// something else is wrong
alert('Please Enter Pasword');
document.login.userPassWord.focus();
return false;
}
else if (document.login.userRePassWord.value ==' ' || document.login.userRePassWord.value != 
document.login.userPassWord.value)
{
// something else is wrong
alert('Your Password Matching not found');
document.login.userRePassWord.focus();
return false;
} 

return true;
}
</script> 

</HEAD>
<BODY bgcolor=lightblue>
<form name=login method="get" 
action="http://localhost:8080/loginexample/login" 
onSubmit="return checkform(this)" >
<center>
<h1>Enter your Name and Pasword </h1><br>
<table border=1>
<tr><td>Enter Your Name :</td>
<td><input type="text" name="userName" value=""></td>
</tr>
<tr><td>Enter Your PassWord :</td>
<td><input type="password" name="userPassWord" value=""></td>
</tr>
<tr><td>Confirm Your PassWord :</td>
<td><input type="password" name="userRePassWord" value=""></td>
</tr>
<tr><td align=center><input type="submit" name="Submit" value="Submit" ></td>
<td align=center><input type="reset" name="reset" value="Refresh"></td>
<table>
</center>
</form>
</BODY>
</HTML>

ConnectionFactory.java


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

public class ConnectionFactory {
	String driverClassName = "com.mysql.jdbc.Driver";
	String connectionUrl = "jdbc:mysql://localhost:3306/vendor";
	String dbUser = "root";
	String dbPwd = "root";

	private static ConnectionFactory connectionFactory = null;

	private ConnectionFactory() {
		try {
			Class.forName(driverClassName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	public Connection getConnection() throws SQLException {
		Connection conn = null;
		conn = DriverManager.getConnection(connectionUrl, dbUser,dbPwd);
		return conn;
	}

	public static ConnectionFactory getInstance() {
		if (connectionFactory == null) {
			connectionFactory = new ConnectionFactory();
		}
		return connectionFactory;
	}
}

LoginServlet.java

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginServlet extends HttpServlet {
	Connection connection = null;
	PreparedStatement ptmt = null;
	ResultSet resultSet = null;

	public LoginServlet() {

	}
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		PrintWriter out = response.getWriter();
		response.setContentType("text/html");
		String userName = request.getParameter("userName");
		String userPass = request.getParameter("userPassWord");
		String userRePass = request.getParameter("userRePassWord");

		try {
			String queryString = "SELECT VendorName FROM venderInfo WHERE VendorPass=?";
			connection = ConnectionFactory.getInstance().getConnection();
			ptmt = connection.prepareStatement(queryString);
			ptmt.setString(1, userPass);
			resultSet = ptmt.executeQuery();
			// Creating Servlet Context object
			if (resultSet.next()
					&& userName.equalsIgnoreCase(resultSet
							.getString("VendorName"))) {
				HttpSession session = request.getSession(true);
				session.setAttribute("loggedVendor", resultSet.getString(1));

				ServletContext context = getServletContext();
				RequestDispatcher dispatcher = context
						.getRequestDispatcher("/success");
				dispatcher.forward(request, response);
				// or you can write whole thing in one line as ........

				// getServletContext().getRequestDispatcher("/success").forward(request,
				// response);

			} else {
				request.setAttribute("wrongUser", userName);

				ServletContext context = getServletContext();
				RequestDispatcher dispatcher = context
						.getRequestDispatcher("/fail");
				dispatcher.forward(request, response);

				// or you can write whole thing in one line as ........
				// getServletContext().getRequestDispatcher("/fail").forward(request,
				// response);
			}

		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		doGet(request, response);
	}

}

SuccessPage.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class SuccessPage extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<body bgcolor=#F3EEF0><h1>");
out.println("<center>");
HttpSession session = request.getSession(false);
out.println("This Is Success Page");
out.println(session.getAttribute("loggedVendor"));
out.println("</center>");
out.println("</h1></body>");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}

Failure.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Failure extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<center>");
out.println("<body bgcolor=pink><h1>");
out.println("This Is Failure Page");
out.println(request.getAttribute("wrongUser"));
out.println("</center>");
out.println("</h1></body>");
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
When you run this application it will display message as shown below:

 

On Success...........

 

On Failure........

 

Download this example code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Tutorial Topics