The website has been updated, checkout below websites.

https://codingvariable.com/

Sessions Tracking in Servlets.

  • Session simply means a particular interval of time.
  • Sessions Tracking is a way to maintain state (data) of a user. It is also known as session management in servlets.
  • Http protocol is stateless so we need to maintain state using session tracking techniques.

Fig 1.1    HTTP is stateless that means each request is considered as the new request.


Why use Session Tracking?
To recognize the user.

Session Tracking Techniques 
    1. Cookies (non-java, mostly used in PHP,Facebook, Amazon,...etc)
    2. URL Rewriting
    3. Hidden Form Field
    4. HttpSessions

Cookies in Servlet.

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

A cookie has a name, a single value, and optional attributes such as a comment, path (for eg. mail.php ), and domain qualifiers (for eg. yahoo.com), a maximum age (expiry time in secs/msecs), and version number.

How Cookies Works

By default, each request is considered a new request. In cookies technique, we add a 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 the request by default. Thus, we recognize the user as the old user.


Types of Cookie

There are 2 types of cookies in servlets.
  1. Non-persistent cookie (Expiry time zero secs.)
  2. Persistent cookie.
Non-persistent cookie

It is valid for single sessions 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 the user logout or sig out.

Note: Gmail uses cookie technique for login.if you disable the cookie, Gmail won't work.

Advantages of Cookies
  1. The simplest technique of maintaining the state.
  2. Cookies are maintained at client side.
Disadvantage of Cookie
  1. It will not work if cookie is disabled from the browser.
  2. Only textual information can be set in a Cookie object.

Cookie class

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.

Constructer of Cookie class


Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified name and value.

How to create Cookie?

Cookie ck = new Cookie("user","shubhamsingh");

response.addCookie(ck);        //adding cookie in the response

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.


MethodDescription
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 a cookie in the response object.
  2. public Cookie[] getCookies(): method of HttpServletRequest interface is used to return all the cookies from the browser.
How to delete Cookie ?

Let see the simple code to delete cookie. It is mainly used to logout or signout 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  

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



A simple example of Servlet Cookies

In this example. we are storing the name of the user in the cookie object and accessing it in another servlet. As we know well that sessions correspond to the particular user. So if you access it from too many browsers with different values, you will get a different value.

fig 1.1 Servlet Cookie example


index.html


<!DOCTYPE html>
<html>
    <head>
        <title>Cookie Example</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
       <form action="Servlet1" method="post">  
            Name:<input type="text" name="userName"/><br/>  
        <input type="submit" value="go"/>  
        </form>  
    </body>
</html>


Servlet1.java


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Shubham Singh (https://shubhamsingh.dev/)
 */
@WebServlet(urlPatterns = {"/Servlet1"})
public class Servlet1 extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (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();  
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
   

}


Servlet2.java


import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Shubham Singh (https://shubhamsingh.dev/)
 */
@WebServlet(urlPatterns = {"/Servlet2"})
public class Servlet2 extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
             Cookie ck[]=request.getCookies();  
            out.print("Hello "+ck[0].getValue());  
  
    out.close();  
        }
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }
    
}



No comments:

Post a Comment