Friday, January 21, 2011

Managing a Login Session in JSP

As we know that the Http protocol is a stateless protocol, that means that it can't persist the data. Http treats each request as a new request so every time you will send a request you will be considered as a new user. It is not reliable when we are doing any type of transactions or any other related work where persistence of the information  is necessary.  To remove these obstacles we use session management. In session management whenever a request comes for any resource, a unique token is generated by the server and transmitted to the client by the response object and stored on the client machine as a cookie. We can also say that the process of managing the state of a web based client is through the use of session IDs. Session IDs are used to uniquely identify a client browser, while the server side processes are used to associate the session ID with a level of access. Thus, once a client has successfully authenticated to the web applicatiion, the session ID can be used as a stored authentication voucher so that the client does not have to retype their login information with each page request. Now whenever a request goes from this client again the ID or token will also be passed through the request object so that the server can understand from where the request is coming. Session  management can be achieved by using the following thing.
1. Cookies: cookies are small bits of textual information that a web server sends to a browser and that browsers returns the cookie when it visits the same site again. In cookie the information is stored in the form of a name, value pair. By default the cookie is generated. If the user doesn't want to use cookies then it can disable them.
2. URL rewriting: In URL rewriting we append some extra information on the end of each URL that identifies the session. This URL rewriting can be used where a cookie is disabled. It is a good practice to use URL rewriting. In this session ID information is embedded in the URL, which is recieved by the application through Http GET requests when the client clicks on the links embedded with a page.
3. Hidden form fields: In hidden form fields the html entry will be like this : <input type ="hidden" name = "name" value="">. This means that when you submit the form, the specified name and value will be get included in get or post method. In this session ID information would be embedded within the form as a hidden field and submitted with the Http POST command.
In JSP we have been provided a implicit object session so we don't need to create a object of session explicitly as we do in Servlets. In Jsp the session is by default true. The session is defined inside the directive <%@ page session = "true/false" %>. If we don't declare it inside the jsp page then session will  be available to the page, as it is default by true.
For the convenience to understand the concept of session management we have made one program.
The code of the program is given below:
Step1:
        Open a New Web application in NetBeans or Ecllips that you prefer.
Step2:
         Paste the code below in index page of your application under web content folder

<%@ page import="java.util.*, java.lang.* , pack1.HelloBean" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<HTML>
    <HEAD>
        <TITLE>Login using jsp</TITLE>
    </HEAD>

    <BODY style="background-color:blue;" >
        <H1>LOGIN FORM</H1>
        <center>  
        <%
        String myname =  (String)session.getAttribute("username");
     
        if(myname!=null)
            {
             out.println("Welcome  "+myname+"  , <br/><br/><br/><br/><br/><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="password" /> </td>
                    </tr>
                </table>
                <br/>
                <input type="submit" value="login" />
               
            </form>
            </center>
            <%
            }
       
           
            %>
       
    </BODY>
</HTML> 



Step3:
       Create a new jsp file with name checkLogin.jsp under the same web content folder and paste the code below. 

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
   <html><head><title>Login Example</title></head><body style="background-color:blue;">
      
           <center>
<%
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            if (username == null || password == null) {

                out.print("<br/><br/><br/><br/><br/>Invalid paramters");
                out.println("<br/><br/><br/><br/><br/><a href=\"index.jsp\">Return to Login</a>");
            }
            // Here you put the check on the username and password
            if (username.toLowerCase().trim().equals("sadique") && password.toLowerCase().trim().equals("arslan")) {
                out.println("<br/><br/><br/><br/><br/>Welcome " + username);
                %>
                <br/><br/><br/><br/><br/>
                <%
                out.println(" <a href=\"index.jsp\">Return to Home</a>");
                session.setAttribute("username", username);
            }
           else
               {
                out.println("<br/><br/><br/><br/><br/>Invalid username and password");
                out.println("<br/><br/><br/><br/><br/><a href=\"index.jsp\">Return to Login</a>");
           }




%></center>
</body></html>


Step4: 
        Create a logout.jsp page under the same web-content folder and paste the code below


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
   <html><head><title>Login Example</title></head><body style="background-color:blue;"><center>
<%

     String username=(String)session.getAttribute("username");
    if(username!=null)
        {
       
           out.println("<br/><br/><br/><br/><br/>Dear " + username+", You have been successfully loged out.");
            session.removeAttribute("username");
            out.println("<br/><br/><br/><br/><br/> <a href=\"index.jsp\">Return to Login</a>");
           
        }
     else
         {
         out.println("<br/><br/><br/><br/><br/>You are already not login <br/><br/><br/><br/><br/><a href=\"index.jsp\">Return to Login</a>");
     }



%> 

</center></body></html>



Step5:
        Finally run the program
Note: (Here username is sadique and password is arslan. However you can change it in your code.) 


I hope blog with help you to crack session management in JSP.