0% found this document useful (0 votes)
32 views6 pages

05 HTTP Sessions

1. HTTP sessions allow servers to maintain stateful interactions with clients by assigning each client a unique session ID and using it to retrieve session-specific data from requests. Cookies are used to pass the session ID back and forth between client and server. 2. A session object is created on the server for each client's first request and can be accessed via request.getSession() to store and retrieve attributes. Common session methods include getId(), isNew(), getCreationTime(), and invalidate(). 3. Cookies are name-value pairs sent from server to client in HTTP responses and back from client to server in subsequent requests. They are used to associate session IDs with clients across requests. Cookies have properties

Uploaded by

nehaagrawal2210
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views6 pages

05 HTTP Sessions

1. HTTP sessions allow servers to maintain stateful interactions with clients by assigning each client a unique session ID and using it to retrieve session-specific data from requests. Cookies are used to pass the session ID back and forth between client and server. 2. A session object is created on the server for each client's first request and can be accessed via request.getSession() to store and retrieve attributes. Common session methods include getId(), isNew(), getCreationTime(), and invalidate(). 3. Cookies are name-value pairs sent from server to client in HTTP responses and back from client to server in subsequent requests. They are used to associate session IDs with clients across requests. Cookies have properties

Uploaded by

nehaagrawal2210
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Deccansoft Software Services Java EE / HTTP Session & Cookies

------------------------------------------------------------------------------------------------------------------------------------------
Working with HTTP Sessions:

HTTP is a stateless protocol i.e. each request from a client is treated as a first request and there was no provision
for retaining any information of the clients from the previous visits. For the web applications to be realistic there
must be a provision of remembering information about the client.

For example
1) If a web application requires a client to be identified, then such clients must initially login and then request
the secure components. The application has to remember such clients who have already logged in till they
log out.
2) In a web based shopping cart application, application has to remember the items selected so far since such
information is required for billing purpose.

To make client and server interaction stateful, concepts like HTTP Cookies and HTTP Session were introduced as
part of HTTP Protocol.

HTTP Session is an object which exists at the server side within the application and created for each client. The
session object for a client is created when the first request arrives from such client. Every session object has its
own unique identification called as Session ID.

Note: The Web Container is responsible for generating these unique ids.

The Session ID will be sent along with the response in the form of a Response Header (actually a Cookie). The
next time client sends a request, the Session ID is sent along with the request cookies. The web container will use
this ID for locating the matching session object. If a session is found with the matching ID, then we can get any
information which we had put in the session during the previous visits of the client. Thus making the client and
server interaction stateful by nature.

The session object will get destroyed if it is idle for a prolonged period of time after which any further request from
the same client will be treated as the first request. The time period for which the session can be idle is
customizable.

Note: In many web servers, the default time out period is 30 minutes.

Using Session Object in Web Component:

A) In a Servlet

HttpSession session = request.getSession(boolean)


Returns the reference of the session object (if session already exists) belonging to the client whose request is being
processed.

If session does NOT exist then:


true --> Create and return a new Session.
false --> Do not Create a Session and return null.

B) In a JSP

By default the reference of a session object is available in all JSP as one of the implicit objects. We can turn off the
session support in JSP by using the following page directive attribute.

<%@ page session = “true” %> [Can use session object in such page]
<%@ page session = “false” %> [Cannot use session object in such page]

1
Deccansoft Software Services Java EE / HTTP Session & Cookies
------------------------------------------------------------------------------------------------------------------------------------------
The Servlets Specification mentions an interface javax.servlet.http.HttpSession which exposes methods of a
session object. Some commonly used methods are:

String = getId()
boolean = isNew()
long = getCreationTime() // when was the session created.
long = getLastAccessTime() // This signifies the time when the latest request has arrived with the matching id.
setMaxInactiveInterval(int seconds) //negative value implies the session will never expire. Such session can be
programmatically abandoned.
int seconds = getMaxInactiveInterval()
invalidate ()

Using session as a scope

session.setAttribute(String, Object)
Object = session.getAttribute(String)
Enumeration = session.getAttributeNames()
session.removeAttribute(String)

------------------------------------------------------------------------------------------------------------------------------------------
sessionDemo.jsp
<html>
<body>
<h1>
Is New : <%= session.isNew()%>
<br><br>
<%= session.getId()%>
<br>
<a href = "sessionDemo.jsp">Visit again</a>
</h1>
</body>
</html>
-------------------------------------------------------------------------------------------------------------------------------
Write a JSP which increments and displays a counter every time a client visits it.
countDemo.jsp
<%
Object obj = session.getAttribute("count");
Integer intObj = (Integer)obj;
if (intObj == null)
{
intObj = new Integer(0);
}
int visits = intObj.intValue();
visits++;
session.setAttribute( "count", new Integer(visits) );
%>
<html>
<body>
<h1>
Visits : <%= session.getAttribute("count") %>
<br>
<a href = "countDemo.jsp">Visit again</a>
</h1>
</body>
</html>

2
Deccansoft Software Services Java EE / HTTP Session & Cookies
-------------------------------------------------------------------------------------------------------------------------------------------------
Cookies are HTTP Header based concept invented by Netscape to overcome statelessness of HTTP Protocol.

Cookie is an object of class javax.servlet.http.Cookie and can hold a name/value pair. It can optionally set properties like
maxAge, path, domain and comment. Cookies travel from server to client as HTTP response headers. These headers will
not be visible to us. An HTTP client like a browser accepts the cookies and would send them along with the request the
next time we send a request from that browser. Cookies are sent from client to the server as part of HTTP request
(headers)

Note: A browser is expected to support 20 cookies from each Web server, 300 cookies in all and may limit cookie size
to 4 KB each.

javax.servlet.http.Cookie is a class. It class has only one Constructor: Cookie (String name, String value)
Cookie name can contain only ASCII alphanumeric characters and cannot contain commas, semicolons, or white space
or begin with a $ character. The cookie's name cannot be changed after creation. Its value can be anything we choose.
The cookie's value can be changed after creation with the setValue method.

String = getName () / there is no setName method since cookie name cannot be changed after creation
String = getValue () / setValue (String)
int seconds = getMaxAge() / setMaxAge (int seconds)
Sending a cookie with age set as zero is a message to the browser to delete an earlier accepted cookie with same name.

To Add a Cookie to the response: response.addCookie(Cookie)


To Retrieve Cookies which have come along with the request: Cookie [] = request.getCookies ()

Types of Cookies:
Non-Persistent Cookie: Cookies which are temporarily stored in the browser memory. These are not shared across
browser instances. They are also called as Session Cookie since they are gone when browser is closed.

Persistent Cookie: Cookies which are stored on the client machine for the duration which we specify. After such time
period, the cookie will expire and browser will discard it. This cookie is shared by all the instances of the browser type
which had accepted the cookie. (For e.g. all instances of Internet Explorer would share such cookie).
--------------------------------------------------------------------- name.jsp ---------------------------------------------------------------
<html>
<body>
<form action='setCookie.jsp' method='post'>
Enter your name : <input type='text' name=”t1” value=””>
<input type='submit' name='submit' value='Proceed'>
</form>
</body>
</html
--------------------setCookie.jsp---------------------------------- --------------------------getCookie.jsp---------------------------
<% <%
String t1Value = request.getParameter (“t1”); String value = null;
if (t1Value == null || t1Value.trim().length()<1 ) Cookie cookies [ ] = request.getCookies ( ) ;
{ if (cookies!= null && cookies.length > 0 ) {
%> for ( int i=0; i< cookies.length; i++ ) {
<jsp:forward page="name.jsp" /> if (cookies[i].getName().equals("mycookie")) {
<% value = cookies [i].getValue ( ) ;
} break;
Cookie ck = new Cookie(“mycookie", t1Value); }
response.addCookie (ck); }
%> }
<html> if (value == null ) {
<body> %> <jsp:forward page="name.jsp" />
<h1> <%
I know your name.... }
<a href='getCookie.jsp'>test</a> %>
</h1> <html>
</body> <body>
</html> <h1> Your name is <%= value %> </h1>
</body>
</html>

3
Deccansoft Software Services Java EE / HTTP Session & Cookies
------------------------------------------------------------------------------------------------------------------------------------------
Headers set by a page are not visible in other pages which are processed in the same request i.e. forward and included
pages. To make the headers visible we have to use the concept of Http Redirection. When an http client is redirected, it
gets a URL in one of the response headers. The client will then send a new request to the specified URL and thus gets
the response from the new page. In redirection, there will be two requests involved
1. The actual request which we explicitly make
2. The request due to redirection and in this request the user is not involved.

Differences between redirect and forward:


Forward happens within the same request context whereas redirection has two separate requests. The headers and
cookies set by a page are not visible in the forwarded page whereas in redirect they are visible. Forward works only
when two resources are in the same server where as in redirection the resources can be in different servers.

response.sendRedirect (String)

NOTE: Request sent due to redirection will be made using request method GET irrespective of the original request
method. If information has to be sent from one page to another in redirection, then Query String should be utilized for
holding such information

--------------------setCookie.jsp------------------------------ --------------------------getCookie.jsp------------------------
<% <%
String t1Value = request.getParameter (“t1”); String value = null;
if (t1Value == null || t1Value.trim().length()<1 ) Cookie cookies [ ] = request.getCookies ( ) ;
{ if (cookies!= null && cookies.length > 0 )
%> {
<jsp:forward page="name.jsp" /> for ( int i=0; i< cookies.length; i++ )
<% {
} if (cookies[i].getName().equals("mycookie"))
Cookie ck = new Cookie(“mycookie", t1Value); {
response.addCookie (ck); value = cookies [i].getValue ( ) ;
Object obj = session.getAttribute ( "myurl" ); break;
if ( obj != null ) }
{ }
session.removeAttribute ( "myurl" ); }
response.sendRedirect ( obj.toString( ) ); if (value == null )
} {
%> session.setAttribute("myurl", "getCookie.jsp");
<html> %> <jsp:forward page="name.jsp" />
<body> <%
<h1> }
I know your name.... %>
<a href='getCookie.jsp'>test</a> <html>
</h1> <body>
</body> You are <%= value %>
</html> </body>
</html>

4
Deccansoft Software Services Java EE / HTTP Session & Cookies
//------------------------------------------------------Person.java---------------------------------------------------------
package demo;

public class Person implements java.io.Serializable


{
private String firstName;
private String lastName;

public Person()
{}

public Person(String firstName, String lastName)


{
this.firstName = firstName;
this.lastName = lastName;
}

public String getFirstName()


{
return firstName;
}

public void setFirstName(String fn)


{
firstName = fn;
}

public String getLastName()


{
return lastName;
}

public void setLastName(String ln)


{
lastName = ln;
}
}

5
Deccansoft Software Services Java EE / HTTP Session & Cookies
------------------------------------------- welcome.html------------------------------------------------------------------
<html>
<body>
<h1>
Enter your name :
<br>
<form action='setdemo.jsp' method='post'>
First Name:
<input type='text' name='firstName' value=''><br>
Last Name:
<input type='text' name='lastName' value=''><br>
<input type='submit' name='submit' value='Proceed'>
</form>
</h1>
</body>
</html>
----------------------------------------------setdemo.jsp-------------------------------------------------------------------
<jsp:useBean id="per" scope="session" class="demo.Person"/>

<jsp:setProperty name="per" property="*" />

<html>
<body>
<h1>
I know your name...
<a href=”getdemo.jsp”>test</a>
</h1>
</body>
</html>
----------------------------------------------getdemo.jsp------------------------------------------------------------------
<jsp:useBean id="per" scope="session" class = "demo.Person"/>

<html>
<body>
<h1>
Welcome
<jsp:getProperty name="per" property="firstName"/>
<jsp:getProperty name="per" property="lastName"/>
</h1>
</body>
</html>

You might also like