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-content
>Meta-Inf
>Web-Inf
>lib
>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
loginsuccess.jsp
Here i want initial page
of my application should be login.jsp.
hence my welcome file
will be login.jsp.
See Below
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
Two servlet i.e.,
LoginServlet.java
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).
LogoutServlet.java
url pattern for LogoutServlet.java class is getLogout.
See Below Example Of Our
Project's web.xml File.
web.xml
<?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">
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.login.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/getLogin</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>logoutservlet</servlet-name>
<servlet-class>com.login.logoutservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>logoutservlet</servlet-name>
<url-pattern>/getLogout</url-pattern>
</servlet-mapping>
</web-app>
login.jsp
- 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"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body><br/><br/><br/><br/>
<center>
<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/>
<input type="submit"
value="Login"
style="width:170px;height:34px;">
</form>
</center>
</body>
</html>
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.*;
@SuppressWarnings("serial")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter
out=response.getWriter();
RequestDispatcher rd;
HttpSession
session=request.getSession();
Connection conn=null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql@123","root","");
String username=request.getParameter("username");
String password=request.getParameter("password");
String query="SELECT password FROM login where
username=?";
PreparedStatement
pst=conn.prepareStatement(query);
pst.setString(1,username);
ResultSet
rs=pst.executeQuery();
if(rs.next()){
if(
rs.getString(1).equalsIgnoreCase(password)){
session.setAttribute("username", username);
rd=request.getRequestDispatcher("/loginsuccess.jsp");
rd.foward(request,
response);
}
else {
out.print("Invalid
Password");
rd=request.getRequestDispatcher("/login.jsp");
rd.include(request,
response);
}
}
else {
out.print("Invalid
Username");
rd=request.getRequestDispatcher("/login.jsp");
rd.include(request,
response);
}
}
catch (SQLException e){
out.print(e.getMessage());
}
catch
(ClassNotFoundException e) {
out.print(e.getMessage());
}
}//end of main
}//end of class
loginsuccess.jsp
- 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"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html
PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body><br/>
<%
if(session.getAttribute("username")==null)
{
response.sendRedirect("login.jsp");
}
else{
String
name=session.getAttribute("username").toString();
%>
<center>Logged
In<br/>
<h3>Welcome</h3>
<h3> <%=name
%></h3>
<form method="post" action="getLogout">
<input
type="submit" value="Logout?">
</form>
</center>
<%}%>
</body>
</html>
when user hit logout button then logoutservlet.java servlet
is
responsible to invalidate the sessions.See below example.
logoutservlet.java
- 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();
session.invalidate();
response.sendRedirect("login.jsp");
}
}
Hope It Will Help
You...:)

No comments