Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

JSP Session Overview

JSP is the Server side programming language. Generally for high level security purpose we use JSP program. But at the same time it is very much important that transaction, login, logout procedure is done successfully.

Java Server Page can work with standard security page, which also works with the session concept. Session is server side object, which is generated through the server-based technology. If we wish to login a page with standard username and password based programming structure, then it is sure that we have implemented session technology in our project.

A session ends when the user closes the browser or after leaving the site. The server will terminate the session after a predetermined period of time.

Features of the Session

Following are the features of session object:

  • A session refers to the entire conversion between a client and a server.
  • Sessions are generally created automatically.
  • The session object allows accessing the client’s session data, managed by the server.
  • The session variable is fixed if there is no incoming session reference.
  • Generally one exception may occur when the session attribute of the page directives is used to turn session off.
  • By default during the given period, the session can persists over multiple connections and/or request.
  • Session is used to maintain state and user identity across multiple page requests.
  • The session object has session scope.
  • The session object is an instance of the javax.servlet.http.HttpSession, which provides access to session data as well as information about the session such as when it was created and when a request for the session was the last request.
  • The session implicit object that is used to provide a connotation amongst the client and the server system. This association or the session are persists over the multiple influences and/or requirements to during a given time period.
  • Sessions are used to preserve state and user identity transversely to multiple page requests process.
  • Basically the session can be maintained either by using cookies or by URL (Uniform Resource Locator) and rewriting.

Now in the following table I will summaries the most beneficial methods which are available to the session object.

No

Method

Description

1

isNew()

The session is measured to be "new" if it has been produced by the server, but the client has not yet acknowledged joining through the session.

2

invalidate()

This method is used to discards the session and releasing any objects that stored as attributes.

3

getAttribute(String)

It Repossesses the object associated with the named attribute. Passing one string types arguments.

4

getAttributeNames()

This function can Retrieves the names of all attributes currently that are associated with the session.

5

setAttribute(String, object)

The Sets of the object to the named attribute. This attribute created if it does not exist.

6

removeAttribute(String)

It is use to removes the object bound with the quantified name from this session.

Table1: Summary of important methods

General using Application, Session and Request Attributes

The capability to share an object between Java Server Pages at the request, session or the application level can momentously enhance your Java Server Pages application. It is significant to note that this object is shared amongst pages moderately than copied and passed between the pages. This point is emphasized in the following example.

The Object which is shared at the presentation level is accessible from all user sessions. This means that the data such as user name or credit card particulars should never be held as the application attributes. Basically it is very good specimen of what can be held at the application level is a hit counter process. It is needed to hold the objects that held at the request level is rare except when we are working with <jsp:include/> and <jsp:forward/> tags which we may be discuss at a later point. Now another point to be noted about the attribute is that they can only hold the objects variables of primitive data types which cannot be shared in this path way.

Now here we are discussing the following example which illustrates the sharing of an object as an application characteristic. The first Java Server Pages creates a new Array object and sets it as an application attribute process:

Listing 1: Sample showing array (build2bceiarray.jsp)

<%
//Define and build an array in the program
  String[] bceiarray = new String[5];
 
  bceiarray[0] = " Welcome ";
  bceiarray [1] = "to ";
  bceiarray [2] = "mr";
  bceiarray [3] = "bool ";
  bceiarray [4] = "tutorials ";
 
//Set application attribute in here
  application.setAttribute("Storedbceiarray", bceiarray);
%>

This second JSP (Java Server Page) gets the presentation attribute.

Point should be remembered that it is used for the cast when retrieving the attributes

Listing 2: Sample for fetching data (fetchingarray.jsp)

<%
//Retrieve application attribute
  String[] ceiArray =
            (String[])applicaton.getAttribute("Storedbceiarray ");
 
//Write out array values
  out.println(ceiArray[0]);
  out.println(ceiArray[1]);
  out.println(ceiArray[2]);
  out.println(ceiArray[3]);
  out.println(ceiArray[3]);
%>

Here we write only out.println () not System.out.println () because it is not a Console based. It is a web based technology.

The following output will be generated from the second JSP.

Welcome to mrbool tutorials.

Login and Registration using JSP Session

Now I will give some example that shows how we can execute the system with username and password. This is an excellent example for developing user authentication website. Here we can learn about the processing to insert the data to MySQL database using Java Server Page. Also we take up knowledge for implementation Session process in the login page.

At first we create a table with table name ceistudent with the following field.

CREATE TABLE `ceistudent`(
  `roll` int(10) unsigned NOT NULL auto_increment,
  `fname` varchar(45) NOT NULL,
  `lname` varchar(45) NOT NULL,
  `emaild` varchar(45) NOT NULL,
  `username` varchar(45) NOT NULL,
  `passwd` varchar(45) NOT NULL,
  `regdate` date NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Example 1:

Listing 3: Sample index page (index.jsp)

 <%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Welcome to Baranagar Computer Educational Institution</title>
    </head>
    <body>
        <form method="post" action="userlogin.jsp">
            <center>
            <table border="1" width="30%" cellpadding="3">
                <thead>
                    <tr>
                        <th colspan="2">Student Login Here….</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>User Name</td>
                        <td><input type="text" name="uname" value="" /></td>
                    </tr>
                    <tr>
                        <td>Password</td>
                        <td><input type="password" name="pass" value="" /></td>
                    </tr>
                    <tr>
                        <td><input type="submit" value="User Login" /></td>
                        <td><input type="reset" value="Reset" /></td>
                    </tr>
                    <tr>
                        <td colspan="2">It is not Registered here!! <a href=" bceireg.jsp">Register Here</a></td>
                    </tr>
                </tbody>
            </table>
            </center>
        </form>
    </body>
</html>

Example 2:bceireg.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Student Registration Page..</title>
    </head>
    <body>
        <form method="post" action="bceiregistration.jsp">
            <center>
            <table border="1" width="30%" cellpadding="5">
                <thead>
                    <tr>
                        <th colspan="2">Enter Student Information Here</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td>First Name</td>
                        <td><input type="text" name="fname" value="" /></td>
                    </tr>
                    <tr>
                        <td>Last Name</td>
                        <td><input type="text" name="lname" value="" /></td>
                    </tr>
                    <tr>
                        <td>Enter Student Email</td>
                        <td><input type="text" name="email" value="" /></td>
                    </tr>
                    <tr>
                        <td>Enter User Name</td>
                        <td><input type="text" name="uname" value="" /></td>
                    </tr>
                    <tr>
                        <td>Password</td>
                        <td><input type="password" name="pass" value="" /></td>
                    </tr>
                    <tr>
                        <td><input type="submit" value="Accept Term & Condition" /></td>
                        <td><input type="reset" value="Reset" /></td>
                    </tr>
                    <tr>
                        <td colspan="2">Already Registered!! <a href="index.jsp">Login Here</a></td>
                    </tr>
                </tbody>
            </table>
            </center>
        </form>
    </body>
</html>

Example 3:bceiregistration.jsp

<%@ page import ="java.sql.*" %>
<%
    String user = request.getParameter("uname");    
    String pwd = request.getParameter("pass");
    String fname = request.getParameter("fname");
    String lname = request.getParameter("lname");
    String email = request.getParameter("email");
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/srimani",
            "root", "cei");
    Statement st = con.createStatement();
    //Here we use insert query code that code is insert all registration information in the database
    int i = st.executeUpdate("insert into ceistudent(fname, lname, email, uname, pass, regdate) values('" + fname + "','" + lname + "','" + email + "','" + user + "','" + pwd + "', CURDATE())");
//current date is a function that is store the current date in the server
 if (i > 0) 
{
        //session.setAttribute("userid", user);
        response.sendRedirect("welcometocei.jsp");
       // out.print("Registration is Successfully Completed!"+"<a href='index.jsp'>Go to Login Page and Try Again</a>");
    } else {
        response.sendRedirect("index.jsp");
    }
%>

Example 4:welcomecei.jsp

Registration is Successful.
Please Login Here <a href='index.jsp'>Go to Login</a>

Example 5:login.jsp

<%@ page import ="java.sql.*" %>
<%
    String userid = request.getParameter("uname");    
    String pwd = request.getParameter("pass");
    Class.forName("com.mysql.jdbc.Driver"); //create jdbc driver for accessing the data from the database
    Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname",
            "root", "cei");
    Statement st = con.createStatement();
    ResultSet rs;
    rs = st.executeQuery("select * from ceistudent where uname='" + userid + "' and pass='" + pwd + "'");
    if (rs.next()) {
        session.setAttribute("userid", userid);
        //out.println("Welcome.." + userid);
        //out.println("<a href='signout.jsp'>Log out</a>");
        response.sendRedirect("complete.jsp");
    } else {
        out.println("Invalid password Please ReEnter<a href="index.jsp">Try Again</a>");
    }
%> 

Example 6:complete.jsp

<%
    if((session.getAttribute("userid") == null)||(session.getAttribute("userid") == "")) {
%>
Student are not logged in the System.<br/>
<a href="index.jsp">Please Login….</a>
<%} else {
%>
Welcome to Baranagar Computer Educational Institution <%=session.getAttribute("userid")%>
<a href="signout.jsp">Log out</a>
<%
    }
%>

Example 7:signout.jsp

<%
session.setAttribute("userid", null);
session.invalidate();
response.sendRedirect("index.jsp");
%>

Hyper Text Transfer Protocol is a concept of stateless protocol which means each time a client retrieves a Web page the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.

But there are following three ways to maintain session between web client and web server technology:

Generally webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.

This is not an efficient way because browsers some time do not support a cookie.

Concept of Hidden Form Fields:A web server is capable of sending hidden HTML form field along with a unique session ID as follows:

<input type="hidden" name="sessionid" value="12345">

This entry means that, when the form is submitted, the name and value are automatically included in the GET or POST data. Now when the web browser sends request back, then the session_id value can be used to keep the track of different web browsers.

This could be an effective way of keeping track of the session but clicking on a regular (<A href...>) hypertext link does not result in a form submission, so in this situation hidden form fields do not support general session tracking.

URL Rewriting:We can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session.

For example, with http://ceimaa.netii.net/index.jsp; sessionid=92318212348981177295, the session identifier is attached as sessionid=92318212348981177295 which can be accessed at the web server to identify the client.

Uniform Resource Locator rewriting is a better way to preserve sessions and works for the browsers when they do not support cookies but here a drawback is that we should have spawn every Uniform Recourse Locator dynamically to assign a sessionID though the page is simple static HTML page.

The Session Object

Java Server Page makes use of servlet that is provided by HttpSession and the Interface which provides a way to identify a user diagonally when more than one page is requested or visit to a Web site and to store information about that user.

Java Server Pages have session tracking enabled and a new HttpSession object is instantiated for each innovative client robotically. Disabling session tracking requires explicitly turning it off by setting the page instruction session attribute to false as follows:

<%@ page session="false"%>

The Java Server Page engine exposes the HttpSession object to the JSP author through the implicitsessionobject process. Herethe sessionobject is now provided to the JSP developer and the programmer can immediately begin storing and retrieving data from the object without any initialization or getSession() procedure.

Processing to Session Tracking Example

Now use the HttpSession object to find out the creation time and also the last-accessed time for a session. We need to associate a new session with the request if one does not already exist.

Listing 4: Sample showing session tracking

 <%@ page import="java.io.*,java.util.*" %>
  <%
     Date ct = new Date(session.getCreationTime());// Process to get session creation time.
     Date lt = new Date(session.getLastAccessedTime());// Process get last access time of this web page.
     String title = "Welcome Back to Baranagar Computer Educational Institution.";
     Integer vc = new Integer(0);
     String vck= new String("vc");
     String userIDKey = new String("userID");
     String userID = new String("BCEI");
     // Check if this is new visitor on our web page.
     if (session.isNew()){
        title = "Welcome to mrbool.";
        session.setAttribute(userIDKey, userID);
        session.setAttribute(vck,  vc);
     } 
     vc = (Integer)session.getAttribute(vck);
     vc = vc + 1;
     userID = (String)session.getAttribute(userIDKey);
     session.setAttribute(vck,vc);
  %>
  <html>
  <head>
  <title>Session Tracking Example here..</title>
  </head>
  <body>
  <center>
  <h2>Session Tracking</h2>
  </center>
  <table border="1" align="center"> 
  <tr bgcolor="lightyellow">
     <th>Show the Session Information</th>
     <th>Value</th>
  </tr> 
  <tr>
     <td>id</td>
     <td><% out.print( session.getId()); %></td>
  </tr> 
  <tr>
     <td>Show the Creation Time</td>
     <td><% out.print(ct); %></td>
  </tr> 
  <tr>
     <td>Time of Last Access</td>
     <td><% out.print(lt); %></td>
  </tr> 
  <tr>
     <td>User ID…</td>
     <td><% out.print(userID); %></td>
  </tr> 
  <tr>
     <td>Number of Visitors</td>
     <td><% out.print(vc); %></td>
  </tr> 
  </table> 
  </body>
  </html>
  

Now save the index.jsp and try to access it using http://localhost:8080/index.jsp. It should be displayed the following result when we would run for the first time:

“Welcome to mrbool”

Session Scope

A session is the time of the user to spends using the application, which ends when they close their bowser, when they go to another web site or when the application designer wants to log out. Session scope is more commonly used then application scope. Session scope allows creating and binding object to a session. Object with a session scope are accessible from pages processing request that are in the same session as the one in which they were created. Object bound to the session are created in the session aware JSP (Java Server Pages). This makes them available to all JSP (Java Server Pages) and servlets in the same session. Session scope is often used for the managing security credentials and for the managing state among multiple pages such as in a web-based wizard. The object bound to session scope should be explicitly removed when no longer needed. The objects created with the session scope are not thread safe and access to them must be synchronized if multiple requests could use the same session object at the same time.

Conclusion

From the above discussion it is clear that if we are working in login page then we have to set up a session system in our programming model. And session is very important for implementing real life web applications. Hope you have understood the functionality and implementation details. Enjoy reading in mrbool !!



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login