Skip to main content

JSP Login Logout Example

In this section we will discuss how to create a simple login and logout example.

This section will describe you all the steps for creating a simple login and logout example. To create a simple login logout example in JSP we will use Eclipse IDE for compile and Tomcat 7 server for deploying the application.
In this application we will fetch the record from database and then matched them to the input value that are given through the user interface i.e. login form.
Example
I am giving here a simple login logout example. We will create this example using JSP. In this example we will take input through a form and we will validate the input record from the record saved into the database table. For this at first we will create a database table and then we will insert some dummy values. Then we will create the JSP pages for different purposes. At first we will create home.jsp page where we will design an interface for the user to input and submit their records then we will create login.jsp page where we will write the code for getting the input field values and the database table records. Here we will write the sql query for fetching the matched record from table. Then we will create welcome.jsp page where we will write the code for showing the valid user name after the value matched. Then we will create error.jsp page where we will write the code for showing the error message after if any problem getting in login to the user. Then finally we will create logout.jsp page where we will write the code for logout of user from the application. In this example we will use the JSP implicit object session and we will use the methods setAttribute() for setting the attribute value in session and getAttribute() method for getting the attribute value from the same session invalidate() method for ending the session or logout from the application.
Database Table
userdetail
CREATE TABLE `userdetail` (             
              `id` int(5) NOT NULL,                 
              `name` varchar(20) DEFAULT NULL,      
              `password` varchar(35) DEFAULT NULL,  
              `usertype` varchar(30) DEFAULT NULL,  
              PRIMARY KEY (`id`)                    
            ) ENGINE=InnoDB DEFAULT CHARSET=latin1
Insert values into the table
insert into `userdetail`(`id`,`name`,`password`,`usertype`) values ( '1','arun','arun','admin')
insert into `userdetail`(`id`,`name`,`password`,`usertype`) values ( '2','deepak','deepak','user')
Values in the table
Directory Structure of application
JSP Code
home.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<!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>Home</title>
</head>
<body>
<%
Connection con= null;
PreparedStatement ps = null;
ResultSet rs = null;

String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/record";
String user = "root";
String password = "root";

String sql = "select usertype from userdetail";

try {
Class.forName(driverName);
con = DriverManager.getConnection(url, user, password);
ps = con.prepareStatement(sql);
rs = ps.executeQuery(); 
%>
<form method="post" action="login.jsp">
<center><h2 style="color:green">JSP Login Example</h2></center>
<table border="1" align="center">
<tr>
<td>Enter Your Name :</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Enter Your Password :</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td>Select UserType</td>
<td><select name="usertype">
<option value="select">select</option>
<%
while(rs.next())
{
String usertype = rs.getString("usertype");
%>
<option value=<%=usertype%>><%=usertype%></option>
<% 
}
}
catch(SQLException sqe)
{
out.println("home"+sqe);
}
%>
</select>
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="submit"/></td>
</table>
</form>
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %> 
<!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>Login</title>
</head>
<body>
<%! String userdbName;
String userdbPsw;
String dbUsertype;
%>
<%
Connection con= null;
PreparedStatement ps = null;
ResultSet rs = null;

String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/record";
String user = "root";
String dbpsw = "root";

String sql = "select * from userdetail where name=? and password=? and usertype=?";

String name = request.getParameter("name");
String password = request.getParameter("password");
String usertype = request.getParameter("usertype");

if((!(name.equals(null) || name.equals("")) && !(password.equals(null) || password.equals(""))) && !usertype.equals("select"))
{
try{
Class.forName(driverName);
con = DriverManager.getConnection(url, user, dbpsw);
ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.setString(2, password);
ps.setString(3, usertype);
rs = ps.executeQuery();
if(rs.next())
{ 
userdbName = rs.getString("name");
userdbPsw = rs.getString("password");
dbUsertype = rs.getString("usertype");
if(name.equals(userdbName) && password.equals(userdbPsw) && usertype.equals(dbUsertype))
{
session.setAttribute("name",userdbName);
session.setAttribute("usertype", dbUsertype); 
response.sendRedirect("welcome.jsp"); 
} 
}
else
response.sendRedirect("error.jsp");
rs.close();
ps.close(); 
}
catch(SQLException sqe)
{
out.println(sqe);
} 
}
else
{
%>
<center><p style="color:red">Error In Login</p></center>
<% 
getServletContext().getRequestDispatcher("/home.jsp").include(request, response);
}
%>
</body>
</html>
welcome.jsp
<%@ 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>Welcome</title>
</head>
<body>
<p>Welcome, <%=session.getAttribute("name")%></p>
<p><a href="logout.jsp">Logout</a>
</body>
</html>
error.jsp
<%@ 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>Login Error</title>
</head>
<body>
<center><p style="color:red">Sorry, your record is not available.</p></center>
<%
getServletContext().getRequestDispatcher("/home.jsp").include(request, response);
%>
</body>
</html>
logout.jsp
<%@ 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>Logout</title>
</head>
<body>
<% session.invalidate(); %>
<p>You have been successfully logout</p>
</body>
</html>
Output
When you will compile and deploy this example using Eclipse and Tomcat 7 then the output will be as follows :
1. Home page will be looked as follows :
2. When you will enter the value and if it matched from the corresponding database table value then the output will be as follows :
3. When you will click on the link for logout then the output will be as follows :
4. But, when you will incorrect value in the respective fields then the output will be as follows :
5. If you left the any field empty or if you don't select the usertype then the output will be as follows :

Comments

Popular posts from this blog

Login and Registration Example in JSP with Session

Those who want to start with jsp and MySQL, this is an excellent example for themselves. Here you can learn how to insert data to MySQL using JSP. Also you can learn about session handling in jsp. 1 2 3 4 5 6 7 8 9 10 CREATE TABLE `members` (    `id` int (10) unsigned NOT NULL auto_increment,    `first_name` varchar (45) NOT NULL ,    `last_name` varchar (45) NOT NULL ,    `email` varchar (45) NOT NULL ,    `uname` varchar (45) NOT NULL ,    `pass` varchar (45) NOT NULL ,    `regdate` date NOT NULL ,    PRIMARY KEY   (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; index.jsp 1 2 3 4 5 6 ...

Timer funcitons in JavaScript: Reminder Script

Timers are used in web pages and we will discuss how to setup one and how to use one with an example. The function setTimeout() in function is used and here is its general syntax. mytime = setTimeout(expression, msec); mytime  is the identifier used to identify the current timeout function.  expression  is the statement that is to be executed after the specified time has ticked off.  msec  is the duration of time in milliseconds after which the expression will be executed.  You can see by using setTimeout function we can execute any function or object after a set of time. For example if msec is set 5000 then the expression will be executed after 5 seconds or 5000 milliseconds.  We will try one example where we will have four period buttons and each button will set a different time for another function to execute and display a alert button. We will call it as a reminder script and we will get one alert box based on the period button we click...

Binary Addition

/* File Name : BinAdd.java */    import java.util.*; public class BinAdd    {  public static String addBit(String a, String b, String c)  { String r=""; if(a.equals("1") && b.equals("0") || a.equals("0") && b.equals("1")) { if( c.equals("0")) r="1"; else { r="0"; c="1"; } } else if( a.equals("0") && b.equals("0") ) { if(c.equals("0")) r="0"; else r="1"; } else if( a.equals("1") && b.equals("1") ) { if(c.equals("0")){ r="0"; c="1"; } else { r="1"; c="1"; } } return c+r; }   public static String add(String a, String b)   { String r=""; int len=a.length(); String carry="0"; for(int i=len-1;i...

Real time changing Clock showing date and time

We can display a clock which will be showing the local time of the client computer by using JavaScript. Note that this time displayed is taken from user computer and not from the server.  We have seen in our  date object example how to display current date and time   where the current date and time is displayed once. Here we will try to display changing clock or real time change in date and time by using  setTimeout function . This setTimeout function we have used to trigger the time display function in a refresh rate of 1000 mill seconds ( 1 Sec ). This refresh rate can be changed to any other value. By changing the value to 5000 the clock will refresh and show the exact time once in every 5 seconds.  Here is the demo of this script and code is given below that.  Sat Apr 23 2016 08:27:22 GMT+0530 (IST)   Here is the code <html> <head> <title>(Type a title for your page here)</title> <script type="text/javascript...