Switch to full style
JSP Code Examples
Post a reply

login using jsp

Sat Jan 24, 2009 1:12 am

Login using JSP Example:
The Login in JSP is based on the Session object, here, there are three files: login(Sign-in) form, check sign-in JSP code, and Logout JSP code. You can change the checks of the login JSP code to follow your program needs. Below, I explain each JSP step for the login process.


1.The Main Login Page: contains login HTML form

:
This file contains the HTML login form written within the JSP tags. A check condition is applied on the session attribute with the name "username" to check whether your website user is already logged in or not. If you are already logged-in, then a sign-out link will appear to the user. Otherwise, the HTML login form will be printed out to the user. The login form contains only two input fields. One for inserting the username and another for the password. The default form method is set to POST, and its action is sent to "checkLogin.jsp" page. This means that when the user clicks the Login button (Or Press enter), the browser will call the page "checkLogin.jsp" while passing the username and password attached in the HTTP-POST method. This login form is in the simplest form as much it can be. Following is the code snippet of the JSP login page:
html code
<HTML>
<HEAD>
<TITLE>Login using JSP</TITLE>
</HEAD>

<BODY>
<H1>LOGIN FORM</H1>
<%
String myname = (String)session.getAttribute("username");

if(myname!=null)
{
out.println("Welcome "+myname+" , <a href=\"logout.jsp\" >Logout</a>");
}
else
{
%>
<form action="checkLogin.jsp">
<table>
<tr>
<td> Username : </td><td> <input name="username" size=15 type="text" /> </td>
</tr>
<tr>
<td> Password : </td><td> <input name="password" size=15 type="text" /> </td>
</tr>
</table>
<input type="submit" value="Login" />
</form>
<%
}


%>

</BODY>
</HTML>


This is code snippet that creates a login form for a web application. The code uses a combination of HTML and JSP tags to create the form and handle the user's input. The code uses the <HTML>, <HEAD>, and <BODY> tags to create the basic structure of the web page. The <TITLE> tag is used to specify the title of the page, which is "Login using JSP". The code uses the <H1> tag to create a heading with the text "LOGIN FORM". The JSP code uses the <% %> tags to enclose scriptlets, which are small pieces of Java code that are executed on the server. The scriptlet starts by declaring a variable named "myname" and assigns it the value of the "username" attribute from the session object using the session.getAttribute("username") method. The scriptlet then uses an if-else statement to check if the value of "myname" is not null. If it is not null, it means that the user is already logged in and the scriptlet will display the message "Welcome "+myname+" , Logout" with a link to logout.jsp.

Otherwise, if the value of "myname" is null, it means that the user is not logged in, so the scriptlet will create a login form using the HTML <form>, <table>, <tr>, <td>, and <input> tags. The form has two input fields for the "username" and "password" and a submit button with the value "Login". The form's action attribute is set to "checkLogin.jsp" which is the page that will process the login request and check the credentials against the database. Once the user submits the form, the input fields will be sent to the checkLogin.jsp page for validation. If the credentials are correct, the checkLogin.jsp page will set the username attribute in the session object and redirect the user to the original page. Otherwise, it will redirect the user back to the login page with an error message.

Some additional things to note:

  • The scriptlet uses the "out.println" method to write output to the web page. This method writes the specified string to the response and appends a newline character to the end of the output.
  • The scriptlet uses the "session" object to store and retrieve the user's login information. The session object is used to store information about a user's session, such as login status, and is available to all pages in the application.
  • The scriptlet uses the "!=" operator to check if "myname" is not equal to null. This is a common way to check if a variable has a value or not in Java.
  • The scriptlet uses the "getattribute" method of the session object to get the value of the "username" attribute and the "setattribute" method to set the value of the "username" attribute in the session object, this allows to track the state of the user across different pages.


Many other features can be included into the Login HTML for more professional usage. For instance, it is highly recommended to add a Captcha for the security purpose of your website. The goal of Captcha is to validate that a current session user is an actual person and not just a scam machine (Bot). Moreover, another fundamental functionality that is recommended to be added is the forget password link. The forget password will be used by the user in case he could not remember the password. Basically, the forgot password link is just a reference that will open another HTML form which should control such a specific scenario. However, in this article, we just focus on the log (in-out) normal scenario.


2. JSP username and password validation:


After user submission, the username and password-filled parameters are passed to checkLogin.jsp file to apply a validation process. The method getParameter of reference request is used to fetch the parameter value using its name as set in the Login form. The first rule of validation is to check If the username and the password are actually included in the HTTP request sent to the checkLogin.jsp file. Otherwise, the website will show a static message as "Invalid parameters". Please check the first If-condition block in the code snippet below:

java code
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
out.println("Checking login<br>");
if (username == null || password == null) {

out.print("Invalid parameters ");
}

// Here you put the check on the username and password
if (username.toLowerCase().trim().equals("admin") && password.toLowerCase().trim().equals("admin")) {
out.println("Welcome " + username + " <a href=\"index.jsp\">Back to main</a>");
session.setAttribute("username", username);
}
else
{
out.println("Invalid username and password");
}




%>

If the parameters are successfully passed. The validation process moves on to the next step. This step verifies if the passed parameters exactly match what you have in your records regarding the specified user. For the simplicity purpose of this example, we hard coded the values "admin" and "admin" as the username and password record that must be matched with the passed parameters. The professional practice of this step is to apply the validation with the records available in the database (e.g., MySQL, PGSQL ..etc.). If you have many registered users on your website or system. Certainly, you will have a data table that holds all the registered users' records. You will need to do a SQL query to check whether the passed user parameters (username & password) correspond to a record in the database. The trim() function is used in this example to remove the white spaces (suffix and prefix) that be wrongly entered by the user while typing the username or password. After all the validation checks are passed successfully, a new JSP attribute is added to the current session with the value of the username parameter. In our case, the attribute name is also a username, but its value is whatever is included in the passed username parameter. Throughout the navigation of the website pages, we can continuously check the availability of the username attribute to confirm if the current user is logged-in (note: each user has its session, which usually expires within 30 minutes in most of the web-servers.). In best practice, an HTML template includes a header, body, and footer. The user login status is usually checked in the header section. If the user is logged in, then special actions and links can appear to the user. The links and actions allowed to the user vary based on the website logic. For example, if the registered user is logged in, then a profile link appears to the user where he can modify his personal information.


3. JSP Logout file: Remove the username attribute :


If the user decides to log out, a log-out process must be triggered to remove the attribute. You can use the logout page below, where the session value for your username attribute is erased.
java code
<%

String username=(String)session.getAttribute("username");
if(username!=null)
{
out.println(username+" loged out, <a href=\"index.jsp\">Back</a>");
session.removeAttribute("username");

}
else
{
out.println("You are already not login <a href=\"index.jsp\">Back</a>");
}



%>

That code snippet handles logout requests for a web application. The code uses a combination of JSP tags and scriptlets to handle the user's request and update the session information. The scriptlet starts by declaring a variable named "username" and assigns it the value of the "username" attribute from the session object using the session.getAttribute("username") method. This allows the scriptlet to check if the user is currently logged in or not. The scriptlet then uses an if-else statement to check if the value of "username" is not null. If it is not null, it means that the user is logged in, and the scriptlet will display the message "username loged out, Back" with a link to index.jsp. After that, the scriptlet will remove the "username" attribute from the session object using the session.removeAttribute("username") method. Otherwise, if the value of "username" is null, it means that the user is already not logged in, so the scriptlet will display the message "You are already not login Back in" with a link to index.jsp.


In the end, a backlink is displayed to the user; it is better to use redirect after some time using javascript or meta tags such as this:
Code:
<META http-equiv="refresh" content="3;URL=index.jsp">

The meta tag above redirects the user to the index.jsp page automatically after 3 seconds.
You can also use JSP redirect function as follows :
Code:
<%
response.sendRedirect("index.jsp");%>




Re: login using jsp

Wed Mar 25, 2009 5:33 am

I love this~~~~~~~
Thank you.

Re: login using jsp

Tue Jan 25, 2011 2:34 pm

Hi,
In your program,there is a bug.That is if you click the logout link,it'll take you to the index page but after that if you click the back button,it'll again take you the welcome page .Please check it....

Re: login using jsp

Thu Jun 30, 2011 1:29 pm

love it
thanks

Re: login using jsp

Tue Jul 26, 2011 7:21 am

Really good one love it.................... :gOOd: :gOOd: :yahoo: :sohappy:

Re: login using jsp

Fri Oct 07, 2011 7:01 am

hi i want to check it from the database please any one help me

Re: login using jsp

Sat Nov 05, 2011 9:50 am

krrish wrote:Hi,
In your program,there is a bug.That is if you click the logout link,it'll take you to the index page but after that if you click the back button,it'll again take you the welcome page .Please check it....

hi every one this is the best solution to the logout problem which logs out user when logout link is clicked,it also solves the problem of url, copying and pasting the url does not open the page after logout

this example consists of a sample.html page which takes name and password as input.
Please enter name as kiran and password as kiran
it then forwards to a login.jsp and if name and password are correct it sends it to a welcome.jsp page which has some links like x.jsp,y.jsp,z.jsp and p.jsp and a logout link.
the codes are shown below and are as follows:

**sample.html**
Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-Control" content="no-cache">
    <meta http-equiv="Expires" content="Sat, 01 Dec 2001 00:00:00 GMT">
    <title>SOLVING LOGOUT PROBLEM EFFICIENTLY USING JSP</title>
    </head>
   
    <body bgcolor="#99FF66">
    <center><h1>login</h1></center>
    <center>
    <form nme="login" method="post" action="login.jsp">
    <table>
     <tr>
      <td>name:</td>
      <td><input type="text" name="name" align="right" /></td>
     </tr>
     <tr>
      <td>password:</td>
      <td><input type="password" name="password" align="right" /></td>
      </tr>
      <tr>
       <td>
       </td>
       <td><center><input type="submit" name="submit" /></center></td>
      </tr>
     </table>
     </form>
    </center>
    </body>
    </html>
   


**login.jsp**
Code:
   
    <%
    response.setHeader("Cache-Control","no-store");
    response.setHeader("Pragma","no-cache");
    response.setDateHeader ("Expires", 0);
    %>
   
    Read more: http://wiki.answers.com/Q/How_do_you_clear_the_browser_cache_in_jsp#ixzz1c6g2F9jR
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Untitled Document</title>
    </head>
   
    <body>
   
    <% String fname=null,fpassword=null;
    try
    {
    session.setAttribute("name",null);
    session.setAttribute("password",null);
    fname=request.getParameter("name");
    fpassword=request.getParameter("password");
    if(fname.equals("kiran")&&fpassword.equals("kiran"))
    {
     session.setAttribute("name",fname);
     session.setAttribute("password",fpassword);
    %>
    <jsp:forward page="welcome.jsp"/>
    <%
    }
    else
    {
     %>
     <jsp:forward page="sample.html"/>
     <%
    }
    }
    catch(Exception e)
    {
     System.out.println("errror"+e);
    }
    %>
    </body>
    </html>
   
   
    **welcome.jsp**
   
   
    <%
    response.setHeader("Cache-Control","no-store");
    response.setHeader("Pragma","no-cache");
    response.setDateHeader ("Expires", 0); 
    %>
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Untitled Document</title>
    </head>
   
   
    <%
    if((session.getAttribute("name"))!=null&&(session.getAttribute("password")!=null))
    {
    %>
      <body bgcolor="#99FF66"><center>
      <p>welcome<%=session.getAttribute("name")%> </p><h1 align="right"><a href="logout.jsp">logout</a></h1>
      <p>&nbsp;</p>
      <p>&nbsp;</p>
      <p>&nbsp;</p><table width="100"><tr><td align="center"><a href="x.jsp">x</a></td><td align="center"><a href="y.jsp">y</a></td></tr>
      <tr><td align="center"><a href="z.jsp">z</a></td><td align="center"><a href="p.jsp">p</a></table>
    </center>
    </body>
    <%
    }
    else
    {
    %>
    <jsp:forward page="sample.html"/>
    <%
     }
    %>
   
    </html>

then the links x.jsp,y.jsp,z.jsp,p.jsp all look same.

**x.jsp**


<%
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0); 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<%
if((session.getAttribute("name"))!=null&&(session.getAttribute("password")!=null))
{
%>
<body bgcolor="#99FF66"><h1 align="center">x</h1>
<h1 align="right"><a href="logout.jsp">logout</a></h1>
<center>
<table width="100"><tr><td align="center"><a href="#">x</a></td><td align="center"><a href="y.jsp">y</a></td></tr>
  <tr><td align="center"><a href="z.jsp">z</a></td><td align="center"><a href="p.jsp">p</a></table>
</center>
</body>
<%
}
else
{
%>
<jsp:forward page="sample.html"/>
<%
}
%>
</html>

**y.jsp**

<%
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0); 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<%
if((session.getAttribute("name"))!=null&&(session.getAttribute("password")!=null))
{
%>
<body bgcolor="#99FF66"><h1 align="center">y</h1>
<h1 align="right"><a href="logout.jsp">logout</a></h1>
<center>
<table width="100"><tr><td align="center"><a href="x.jsp">x</a></td><td align="center"><a href="#">y</a></td></tr>
  <tr><td align="center"><a href="z.jsp">z</a></td><td align="center"><a href="p.jsp">p</a></table>
</center>
</body>
<%
}
else
{
%>
<jsp:forward page="sample.html"/>
<%
}
%>
</html>

**z.jsp**

<%
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0); 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<%
if((session.getAttribute("name"))!=null&&(session.getAttribute("password")!=null))
{
%>
<body bgcolor="#99FF66"><h1 align="center">z</h1>
<h1 align="right"><a href="logout.jsp">logout</a></h1>
<center>
<table width="100"><tr><td align="center"><a href="x.jsp">x</a></td><td align="center"><a href="y.jsp">y</a></td></tr>
  <tr><td align="center"><a href="#">z</a></td><td align="center"><a href="p.jsp">p</a></table>
</center>
</body>
<%
}
else
{
%>
<jsp:forward page="sample.html"/>
<%
}
%>
</html>

**p.jsp**

<%
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0); 
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>
<%
if((session.getAttribute("name"))!=null&&(session.getAttribute("password")!=null))
{
%>
<body bgcolor="#99FF66"><h1 align="center">p</h1>
<h1 align="right"><a href="logout.jsp">logout</a></h1>
<center>
<table width="100"><tr><td align="center"><a href="x.jsp">x</a></td><td align="center"><a href="y.jsp">y</a></td></tr>
  <tr><td align="center"><a href="z.jsp">z</a></td><td align="center"><a href="#">p</a></table>
</center>
</body>
<%
}
else
{
%>
<jsp:forward page="sample.html"/>
<%
}
%>
</html>

and finally on logout the code is as follows :

**logout.jsp**

<%
response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0); 
%>
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>

<%
session.removeAttribute("name");
session.removeAttribute("password");
session.invalidate();
%>
<jsp:forward page="sample.html"/>
</body>
</html>

Thats it hope it solves the logout problem

for any queries contact me at [email protected] or [email protected]

Re: login using jsp

Mon Nov 07, 2011 7:21 am

Guest wrote:Thats it hope it solves the logout problem

for any queries contact me at [email protected] or [email protected]


There is still a problem, it did not work for me.

Re: login using jsp

Mon Jan 02, 2012 2:16 pm

mahes wrote:hi i want to check it from the database please any one help me

make class for connection then
write the name of the next page in form tag
example <form action="pagename.jsp">
in the second page we import the class file which make the connection and retrieving data from the database and check the username/password
example <%@page import="Exam.Validation" %>
<jsp:useBean class="Exam.Validation" id="vl" scope="session"></jsp:useBean>
then we take the user name and password form the varriable name of textbox form fist page and pass to the validation class
example <% String s=request.getParameter("Ut"); %>
<% String p=request.getParameter("Pt"); %>
and wirte the syntax if u/p wrong to forward the page
example <% if (!vl.validation(s, p ))response.sendRedirect("index.jsp?msg= invalid user Name/password"); %>

Re: login using jsp

Mon Jan 23, 2012 7:23 pm

Nicely Written Code...!!

Post a reply
  Related Posts  to : login using jsp
 develop a login page- login servlet - ServletContext     -  
 login using Ajax     -  
 php login with session     -  
 ASP.NET 2.0 Login Controls     -  
 Ajax Login     -  
 Send login information     -  
 Login using session with php and mysql     -  
 login using sessionid or time     -  
 code for login by jsp and ajax     -  
 Cookie based login in php     -  

Topic Tags

Servlets/JSP