Jsp Servlet Login And Logout System With Mysql Database


-Here we are going to create a complete login system using Jsp and Servlet.

-Open Your Eclipse IDE
  • Create a dynamic web project in eclipse.
  • Add MySql connector jar file to your project.
  • Now in src directory create two servlet give name as Loginservlet.java and Logoutservlet.java.
  • Now in web-content directory create two jsp file give name as login.jsp and loginsuccess.jsp.
  • A web.xml(deployment descriptor) file will be created inside web-inf folder present inside web-content directory(Note:while creating a dynamic web project select Dynamic Web Module Version as 2.5 OR Higher,Make Sure You Check Generate web.xml Deployment Descriptor Box,It will create web.xml file for you otherwise you have to create manually).

-So We Have Created Files For Our Project See Below.
 -Inside Web-Content
  • login.jsp
  • loginsuccess.jsp
-Inside src Folder
  • LoginServlet.java class
  • LogpoutServlet.java class
-After Creating All These Files.

-Look Inside web.xml 

-web.xml should contain.
  • <welcome-file> tag inside <welcome-file-list></welcome-file-list> tag.
  • servlet name and servlet class inside <servlet></servlet> tag and now servlet-name and url pattern inside <servlet-mapping></servlet-mapping> tag.
Here we have two jsp files i.e.,
login.jsp and 

Here i want initial page of my application should be login.jsp.
hence my welcome file will be login.jsp.

See Below

Two servlet i.e.,
url pattern for LoginServlet.java class is getLogin
(you will be able to create url pattern while creating a servlet,you can give any name to url pattern).

url pattern for LogoutServlet.java class is getLogout.

See Below Example Of Our Project's web.xml File.
 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">






  • Here in this login.jsp we have created a form  with username and password fields to take input from the user and a submit button to submit the form.
  • Here we used post method.
  • Action is getLogin i.e.,when user hit submit button getLogin URL is responsible to process the form parameters and authenticate them.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
 <h3>Login Form</h3>
 <form method="post" action="getLogin">
  Username:<input type="text" name="username"  /><br/><br/>
  Password:<input type="text" name="password" /><br/><br/>
 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 <input  type="submit" value="Login"             style="width:170px;height:34px;">  

LoginServlet.java(url pattern is getLogin :)
Here in LoginServlet.java 
  • We are extracting the form parameters and processing them i.e.,username and password.
  • Setting the content type as text/html.
  • Getting the PrintWriter object as out through the factory method getWriter() of HttpServletResponse,writer object will help us to print text on browser.
  • Using the RequestDispatcher Interface for Servlet Collaboration,this interface can be used to include or forward the content of another resource also ex. loginsuccess.jsp, it has two methods include and forward,we can get the instance of RequestDispatcher through factory method i.e., getRequestDispatcher() of HttpServletRequest.
  • Using the HttpSession interface for session management,HttpServletRequest factory method getSession() provide the instance of HttpSession,using this instance we can set and get session attributes of the session scope.
  • Now registering the driver for database connection.
  • Creating the connection by providing url,username and password using the DriverManager  class method i.e., getConnection(url,username,password) takes url,username and password as argument.
  • Now executing the query for checking username and password,if username and password is correct then displaying appropriate message and forwarding the same request to loginsuccess.jsp. or if username or password is incorrect then displaying appropriate message and including the login.jsp again.
  • If username and password is correct then setting the username in  session scope,so on loginsuccess.jsp we can check if user is logged in or not by getting the session attributes.
Thats All For LoginServlet.java see below…
package com.login;

import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*; 
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  PrintWriter out=response.getWriter();
  RequestDispatcher rd;
  HttpSession session=request.getSession();
  Connection conn=null;
  try { 

String username=request.getParameter("username");
String password=request.getParameter("password");
String query="SELECT password FROM login where username=?";
  PreparedStatement pst=conn.prepareStatement(query);
  ResultSet rs=pst.executeQuery();
   if( rs.getString(1).equalsIgnoreCase(password)){
   session.setAttribute("username", username);
   rd.foward(request, response); 
    else {
    out.print("Invalid Password");
    rd.include(request, response);

  else {
   out.print("Invalid Username");
   rd.include(request, response);
  catch (SQLException e){
  catch (ClassNotFoundException e) {
 }//end of main
}//end of class

  • Here on this page first we are checking by getting the session attribute username that we have set in LoginServelt.java as username using if{} else{} statement.
  • If we got session.getAttribute("username")==null then
  • user can't access this page and they will be redirected to login.jsp.
  • Else user can access this page.
  • After login we are displaying
<%@ page language="java"
contentType="text/html; charset=ISO-8859-1"

<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
  String name=session.getAttribute("username").toString();

 <center>Logged In<br/> 
 <h3> <%=name %></h3>
<form method="post" action="getLogout">
 <input type="submit" value="Logout?">
when user hit logout button then logoutservlet.java servlet is
responsible to invalidate the sessions.See below example.

  • In logoutservlet.java we are invalidating the session.
  • When user hit the logout button on loginsuccess.jsp page this servlet is responsible to invalidate or destroy the sessions,and redirect to initial page of our project application i.e.,login.jsp :).
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class logoutservlet extends HttpServlet {

protected void doPost(HttpServletRequest request,HttpServletResponse response) 
throws ServletException, IOException {

   HttpSession session=request.getSession();
Hope It Will Help You...:)

No comments

You May Like Also

Programming Knowledge

Java JDK
Reversing String in Java
Java Generic Concept With Simple Example
Java Generic Objects Behavior In Non-Generic Area
Creating Connection With MySql Databse Using Java Application
Performing Database Operations Java MySql Insert Update Delete Select
Java Inserting Data in MySql Databse Table
Java Basic Login System Using MySql Database Table
JSP Login System Using MySql Databse
Jsp Servlet Login And Logout System Using Mysql Database Table
What is jdk in Java?
Exaplain inheritance in Java with example?
Exaplain polymorphism in Java with example?
Exaplain abstraction in Java with example?
Exaplain encapsulation in Java with example?
What is the use of this keyword in Java?
Explain ArrayList With Example
Explain LinkedList With Example
Explain Vector Class With Example
Explain Vector Class With Example
Generics in java with example
Behavior of generic objects
How can i pass generic class to a method in java
How to create a login system in jsp using mysql database?
How to create a login and logout system in jsp & servlet using mysql database?
How to connection a simple Java application with mysql database?
How to insert values in mysql databse usiong Java applications?
Perform insertion, retrieval, updatation and delete operations?
How to create a simple login system in java using mysql database?

PHP Login System Using MySql Database
PHP Complete Login System With Session And Logout Using MySql Database