1.What is Session Tracking
Session simply means particular period of time.
Session tracking is the way to maintain state of user or client
across the multiple requests during the session so we need to maintain state
using session tracking techniques.
All web applications are stateless because they are using
stateless protocol Http protocol.Http
There are four techniques used in Session tracking:
1. Hidden
Form Field
2. Cookies
3. URL
Rewriting
4. HttpSession
2.Why Http is designed as stateless protocol?
If http is statefull protocol for multiple requests are
given by client to web application.single connection will be used between
browser and webserver across the multiple requests.this may make clients to engage
connections with webserver for long time even though the connections are
idle.due to this webserver may reach to maximum connections even though most of
the connection are idle .
To overcome that problem http is given as stateless protocol so no
client can engage connection with webserver for longtime .more over the
connection will be closed automatically at the end of each request related
response generation .In internet environment there is a chance to having huge
amount of clients for each website it is recommended to have stateless behavior
for http.
State full web application:
If web application is
capable of remembering a client data during a session across the multiple
request then that web application is called as state full web application.
In statefull web application the web resource program can use the
data of previous request while processing current request that means while
processing request2 it can use request1 data..
Even though http is stateless protocol we can make our web
application as statefull application for this we need to use session tracking .
3.What is Hidden Form Field?
In case of Hidden Form Field a hidden (invisible) text
field is used for maintaining the state of a user.
In such case, we store the information in the hidden field and get
it from another servlet. This approach is better if we have to submit form in
all the pages and we don't want to depend on the browser.
<input type="hidden" name="uname" value="Vimal Jaiswal">
Advantages:
1. It
will always work whether cookie is disabled or not.
2. The
basic html knowledge is enough.
3. This
can be used along with all kind of server side technologies and supports all
kind of web servers, application servers.
4. All
browsers support this technique.
Disadvantage:
1. Extra
form submission is required on each page.
2. Only
textual information can be used.it does not hold java objects.
3. It
not provides data secrecy we can view data using view page option of browser.
4. Hidden
field data travels over the network along with request and response so network
traffic will increase.
5. While
creating each dynamic form page we need to add the previous form pages data as
hidden box values this is burden to the programmer.
index.html
<form action="servlet1">
Name :<
input type="text" name="username"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
Import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet
(HttpServletRequest request, HttpServletResponse response)
{
try {
response.setContentType
("text/html");
PrintWriter out = response.getWriter
();
String n=request.getParameter
("username");
out.print("Welcome "+n);
//creating form that have invisible textfield
out.print
("<form action='servlet2'>");
out.print
("<input type='hidden' name='uname' value='"+n+"'>");
out.print
("<input type='submit' value='go'>");
out.print
("</form>");
out.close
();
} catch (Exception e) {System.out.println
(e) ;}
}
}
SecondServlet.java
Import java.io.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
Public class SecondServlet extends HttpServlet {
Public void doGet
(HttpServletRequest request, HttpServletResponse response)
try {
response.setContentType
("text/html");
PrintWriter out = response.getWriter
();
//Getting the value from the hidden field
String n=request.getParameter
("uname");
out.print
("Hello "+n);
out.close
();
} catch (Exception e){System.out.println(e);}
}
}
web.xml
<Web-app>
<Servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<Servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<Servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<Servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
4.What is URL Rewriting?
In URL rewriting, we append a token or identifier to the URL of
the next Servlet or the next resource. We can send parameter name/value pairs
using the following format:
url? name1=value1&name2=value2
A name and a value is separated using an equal = sign, a parameter
name/value pair is separated from another parameter using the ampersand
(&). When the user clicks the hyperlink, the parameter name/value pairs
will be passed to the server. From a Servlet, we can use getParameter () method
to obtain a parameter value.
Advantages:
1. It
will always work whether cookie is disabled or not (browser independent).
2. Extra
form submission is not required on each page.
Disadvantages:
1. It
will work only with links.
2. It
can send only textual information.
index.html
<form action="servlet1">
Name :<
input type="text" name="username"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doGet
(HttpServletRequest request, HttpServletResponse response){
try {
response.setContentType
("text/html");
PrintWriter out = response.getWriter
();
String n=request.getParameter
("username");
out.print
("Welcome "+n);
//appending the username in the query string
out.print
("<a href='servlet2? Uname="+n+"'>visit</a>");
out.close
();
} catch (Exception e) {System.out.println
(e) ;}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet
(HttpServletRequest request, HttpServletResponse response)
try {
response.setContentType
("text/html");
PrintWriter out = response.getWriter
();
//getting value from the query string
String n=request.getParameter
("uname");
out.print
("Hello "+n);
out.close
();
} catch (Exception e) {System.out.println
(e) ;}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<Servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
5.What is Cookies?
Cookies are the small textual information which
allocates memory at client side by remembering client data across the multiple
requests during session.
The web resource program of a web application
creates cookies at server side but these cookies come to client side along with
response and allocate memory at client side.Cookies are stored in the cache of
the browser.After that if request is sent by the user, cookie is added with
request by default. Thus, we recognize the user as the old user.
There are 2 types of cookies in servlets.
1. Non-persistent
cookie/in memory cookies
2. Persistent
cookie
Non-persistent cookie
It is valid for single session only. It is
removed each time when user closes the browser.
Persistent cookie
It is valid for multiple sessions. It is not removed each time when user
closes the browser. It is removed only if user logout or sign out.
Advantage
1. Simplest
technique of maintaining the state.
2. Cookies
are maintained at client side.
3. This
can be used along with all kind of server side technologies and supports all
kind of web servers, application servers.
Disadvantage
1. It
will not work if cookie is disabled from the browser.
2. Only
textual information can be set in Cookie object.
3. Cookies
can delete explicitly through browser window settings it may fail session
tracking.
4. There
is a restriction on no of cookies in browser window.
5. Cookie
based solutions work only for HTTP clients.
Note: Gmail uses
cookie technique for login. If you disable the cookie, Gmail won't work.
Cookie class
Javax.servlet.http. Cookie classthat
implements Serializable and Cloneable interfaces. It provides the functionality
of using cookies. It provides a lot of useful methods for cookies.
Constructor of Cookie class
|
Constructor
|
Description
|
|
Cookie()
|
Constructs
a cookie.
|
|
Cookie(String
name, String value)
|
Constructs
a cookie with a specified name and value.
|
Useful Methods of Cookie class
There are given some commonly used methods of the Cookie class.
|
Method
|
Description
|
|
public
void setMaxAge(int expiry)
|
Sets
the maximum age of the cookie in seconds.
|
|
public
String getName()
|
Returns
the name of the cookie. The name cannot be changed after creation.
|
|
public
String getValue()
|
Returns
the value of the cookie.
|
|
public
void setName(String name)
|
Changes
the name of the cookie.
|
|
public
void setValue(String value)
|
Changes
the value of the cookie.
|
Other methods required for using Cookies
|
For
adding cookie or getting the value from the cookie, we need some methods
provided by other interfaces. They are:
1. public void addCookie (Cookie
ck): method of
HttpServletResponse interface is used to add cookie in response object.
2. Public Cookie [] getCookies (): method of HttpServletRequest
interface is used to return all the cookies from the browser.
|
6.How to create Cookie?
Cookie ck=new Cookie
("user”,sonoo jaiswal"); //creating cookie object
response.addCookie (ck); //adding cookie in the response
7.How to delete Cookie?
Let's see the simple code to delete cookie. It is mainly used to
logout or sign out the user.
Cookie ck=new Cookie ("user",""); //deleting value of cookie
ck.setMaxAge (0); //changing the maximum age to 0 seconds
response.addCookie (ck); //adding cookie in the response
8.How to get Cookies?
Let's see the simple code to get all the cookies.
Cookie ck [] =request.getCookies ();
for (int i=0; i<ck.length; i++) {
out.print ("<br>"+ck[i].getName ()
+" "+ck[i].getValue ()); //printing name and value of cookie
}
index.html
<form action="servlet1" method="post">
Name :<
input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost
(HttpServletRequest request, HttpServletResponse response)
{
try {
response.setContentType
("text/html");
PrintWriter out = response.getWriter
();
String n=request.getParameter
("userName");
out.print ("Welcome "+n);
Cookie ck=new Cookie
("uname", n); //creating cookie object
response.addCookie (ck); //adding cookie in the response
//creating submit button
out.print
("<form action='servlet2'>");
out.print ("<input type='submit' value='go'>");
out.print
("</form>");
out.close ();
} catch (Exception e) {System.out.println
(e) ;}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost
(HttpServletRequest request, HttpServletResponse response)
{
try {
response.setContentType
("text/html");
PrintWriter out = response.getWriter
();
Cookie ck [] =request.getCookies
();
out.print ("Hello "+ck
[0].getValue ());
out.close ();
} catch (Exception e) {System.out.println
(e) ;}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
9.What is HttpSession?
HttpSession object allocates memory on server
and remember the client data across the multiple requests in the form of
session attribute values.
HttpSession object is one per browser window
(client) so each HttpSession object can be used to remember client data during
session.
HttpSession object means it is the object of
servlet container supplied java class implementing javax.servlet.http.
HttpSession interface.
Every HttpSession object contains sessionId andthe container uses
this id to identify the particular user. An object of HttpSession can be used
to perform two tasks:
1. bind
objects
2. View
and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.
Working with HttpSession:
To create HttpSession Object:
The HttpServletRequest interface provides two methods to get the
object of HttpSession:
1. public
HttpSession getSession (): Returns
the current session associated with this request, or if the request does not
have a session, creates one.
2. public
HttpSession getSession (false): Returns
the current HttpSession associated with this request or, if there is no current
session this method returns null (indicates new HttpSession object can not be
created).if it true same as 1 method.
Commonly used methods of HttpSession interface
1. Public
String getId (): Returns a
string containing the unique identifier value.
String id=ses.getId ();
2. public
long getCreationTime (): Returns
the time when this session was created, measured in milliseconds since midnight
January 1, 1970 GMT.
Long ms=ses.getCreationTime ();
Date d=new Date (ms);
3. public
long getLastAccessedTime ():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight
January 1, 1970 GMT.
Long ms=ses.getLastAccessTime ();
Date d=new Date (ms);
4. public
void invalidate (): Invalidates
this session then unbinds any objects bound to it.
5. getServletContext
(): to get the access to
ServletContext object.
ServletContextsc=ses.getServletContext ();
6.isNew (): to know whether session is new or not
(not send to browser).
boolean b=ses.isNew ();
10.Session Inactive interval or Session Idle timeout?
If the session object is continuously idle for certain amount of
time then it will be invalidated automatically. The default session idle
timeout period is 30 mints (in most of the servers).But this can be done
through explicitly either using programmatic approach or declarative approach.
Ses.setMaxInactiveInterval (1500); //millisesc.
In web.xml:
<web-app>
<session-config>
<session-timeout>20</session-timeout>//20 mints
</session-config>
</web-app>
Once session idle timeout period or maxInactiveInterval period is
completed the underlying webserver automatically expires the session (invalid
the session).
To know current maxInactiveInterval/session timeout period:
Int t=ses.getMaxInactiveInterval ();
11.If we set sessionId Timeout period in both programmatic and declarative approach with two different values. Can you tell me which value will be effected finally?
Since the code of servlet program executes after the web.xml code
so the time specified through programmatic approach will be efected by
overriding the time specified through declarative approach.
Session Attribute:
In Httpsession object the client data will be preserved in the
form of session attribute values.
To create or modify Attribute:
Ses.setAttribute(“age”,new Integer(30));
To read session Attribute value:
Integer s=(Integer)ses.getAttribute(“age”);
To remove the session Attribute:
Ses.removeAttribute (“age”);
12.While working with httpsession object based application what happens if the underlying server restarted In the middle of the session?
The session will be continued.Server collects the data of
Httpsession object and writes to files through serialization process having
session id when programmer shutdown the server when server restarted
httpsession object will be continued having old session id and old session data
by reading data from the file through deserialization process due to this
session will be continued even though the server is restarted In the middle of
session.
Advantages:
1. Httpsession objects allocates the
memory on server holding client data during session as session attributes.so
there will be data secrecy for client session data.
2. Client data during session will not be
travel along with request and response over the network so this reduces the
network burden between client and server.
3. The session attributes of httpsession
objects can take java objects as values.
4. All java based webservers and
application servers support this technique.
5. This technique allows the programmer
to specify session idle timeout period to invalidate inactive session objects.
Disadvantages:
1. Httpsession objects allocate the
memory on server this increases burden on server.
2. If cookies are restricted coming to
browser window this technique fails to perform session tracking.
13.How to notify an object in session when session is invalidated or timed-out?
If we have to make sure an object gets notified when session is
destroyed, the object should implement
javax.servlet.http.HttpSessionBindingListener interface. This interface defines
two callback methods – valueBound () and valueUnbound () that we can define to
implement processing logic when the object is added as attribute to the session
and when session is destroyed.
14.How many session will be created if the same user uses two different browser window?
If two different browser instances were used for example : FireFox
and IE then two session will be created,But if browser tab is used then a
single session will be created.
No comments:
Post a Comment