Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Jsp JSP Login Logout Example

Related Tutorials


 
 

Share on Google+Share on Google+

JSP Login Logout Example

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

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.

Here is the video tutorial that explains you how to create JSP Login form backed with MySQL database.

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 :

Download Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: April 17, 2013

Related Tutorials

Discuss: JSP Login Logout Example  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:8
bikramm aryal
April 17, 2013
i like this site

Roseindia.net is very helpful to people who are economically pour and had interest in programminp. It is best site for online self study . I suggest everyone to visit http://roseindia.net for free online script help.
A man
July 16, 2013
Thanks

It took me hours to find a log out script. But this one works: "<% session.invalidate(); %>". Thanks!!!!
irshad
September 30, 2013
JSP,DB,MYSQL,JAVA

i like this site
Satinder
October 7, 2013
This site is very much helpful

As i started developing java applications,i got much help from this site... Here are lots of examples along with its explanations
Dinesh P
November 25, 2013
JSP

i developed this code but it is not validating... why.. please any one help me.. to find solution.. for this code.. <%@ 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>JSP Page</title> </head> <body> <%! String dbusername; String dbpassword; %> <% String username=request.getParameter("username"); String password=request.getParameter("password"); out.println(username); out.println(password); Connection con=null; Statement stmt=null; PreparedStatement pstmt=null; ResultSet rs=null; try { String driver="oracle.jdbc.driver.OracleDriver"; Class.forName(driver); con= DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); String dbQuery="select * from Login"; stmt=con.createStatement(); rs=stmt.executeQuery(dbQuery); dbusername =rs.getString("username"); dbpassword =rs.getString("password"); if(rs.next()) { if((username.equals("dbusername") && password.equals("dbpassword"))) { session.setAttribute("username",dbusername); response.sendRedirect("Home.jsp"); } else { response.sendRedirect("Error.jsp"); } } } catch(Exception e) { } %> </body> </html>
dskecse
January 9, 2014
how about creating a class?

have u ever heard of separation of concerns? what about defining some business logic for user authorization in a java class and not just using scriplets?
Jay
January 13, 2014
Can somebody help?

I like that idea by dskecse! But I have another question. I have 10 people who can login with usertype='user' How can I show only one 'admin' and one 'user' in the dropdown? Thanks!
aftab
February 11, 2014
Error in execution

i am getting an error on browser . type Status report message /jspLoginLogout/ description The requested resource is not available. Apache Tomcat/7.0.42 what should i do
DMCA.com