Thursday, July 5, 2018

HttpSession interface

  • Container creates a session id for each user.
  • The 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.
Get the HttpSession object:

The HttpServletRequest interface provides two methods to get the object of HttpSession:


1. public HttpSession getSession(): 
  • If the session already exist, it will return existing session else create a new session
2. public HttpSession getSession(boolean create):
  •  If create is true, Always returns a new session.
  • If create is false returns a existing session.

Commonly used methods of HttpSession interface:


  1. public String getId():Returns a string containing the unique identifier value.
  2. public long getCreationTime():Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
  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.
  4. public void invalidate():Invalidates this session then unbinds any objects bound to it
Creating a New Session

HttpSession session = request.getSession();  // If the session already exist, 
                                                                           it will return existing  session else create a new session
HttpSession session = request.getSession(true); //Always returns a new session
session.setAttribute("uname","Bharath");
        
Getting Existing Session

HttpSession session = request.getSession(false);  //Always returns existing session
String name = (String)session.getAttribute("uname");  

Destroying a Session

session.invalidate();

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&??


Advantage of URL Rewriting:
  • It will always work whether cookie is disabled or not (browser independent).
  • Extra form submission is not required on each pages.

Disadvantage of URL Rewriting:
  • It will work only with links.
  • It can send Only textual information.

Hidden Form Field

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="Bharath">

Advantage of Hidden Form Field:
  • It will always work whether cookie is disabled or not.
 Disadvantage of Hidden Form Field:
  • It is maintained at server side.
  • Extra form submission is required on each pages.
  • Only textual information can be used.

Cookies in Servlet


A cookie is a small piece of information that is persisted between the multiple client requests.

By default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is 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.

Types of cookies in servlets:
  • Non-persistent cookie
  • 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 session . It is not removed each time when user closes the browser. It is removed only if user logout or sign out.

Advantage of Cookies:
  • Simplest technique of maintaining the state.
  • Cookies are maintained at client side.
Disadvantage of Cookies:
  • It will not work if cookie is disabled from the browser.
  • Only textual information can be set in Cookie object.
 Cookie class:
javax.servlet.http.Cookie

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:


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.
Create Cookie:

Cookie ck=new Cookie("user","sonoo jaiswal"); //creating cookie object 
response.addCookie(ck); //adding cookie in the response

Delete Cookie:

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

Get 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 
}