Servlets Cookies Handling

Advertisements

Session Tracking in Servlet Servlet Hidden Form

Cookies Handling in Servlet

Cookies are text files stored on the client computer and they are kept for various information like name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

Cookies are created using Cookie class present in Servlet API. Cookies are added to response object using the addCookie() method. This method sends cookie information over the HTTP response stream. getCookies() method is used access the cookies that are added to response object.

In Http Session technique, container internally generates a cookies for transferring the session ID between server and client. Apart from container generated cookie a servlet programmer can also generate cookies for storing the data for a client.

How Cookie works

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 (chrome, firefox) at client side. 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.

coockie tracking in servlet

When use cookies ?

When session ID is not required and when less number of input values are submitted by client in that case in place of using HttpSession Technique you can use cookies Technique to reduce the burden on server.

Points to Remember

  • Cookies is pressistance resource which is stores at client location.
  • We can store 3000 cookies in cookies file at a time.
  • The cookies are introduced by net scape communication.
  • Cookies files exist up to 3 year.
  • Size of cookies is 4 kb.

Type of Coockies

There are two types of cookies, those are given below;

  • In-memory cookies or pre session cookies
  • Persistent cookies

In-memory cookies: By default cookie is in-memory coockie, This type of cookie is lives until that browser is destroy(close). It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookies: Presestent cookie lives on a browser until its expiration time is reached it means , eventhough you close or reopen the browser but still the cookie exists on the browser. 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 signout.

Cookie class

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a some constructor and methods for cookies.

Constructor of Cookie class

ConstructorDescription
Cookie()Used for constructs a cookie.
Cookie(String name, String value)Used for constructs a cookie with a specified name and value.

Methods of Cookie class

MethodsDescription
public void setMaxAge(int expiry)It is used for Sets the maximum age of the cookie in seconds.
public String getName()It is used for Returns the name of the cookie. The name cannot be changed after creation.
public String getValue()It is used for Returns the value of the cookie.
public void setName(String name)It is used for changes the name of the cookie.
public void setValue(String value)It is used for changes the value of the cookie.
public void addCookie(Cookie ck)It is method of HttpServletResponse interface which is used to add cookie in response object.
public Cookie[] getCookies()It is method of HttpServletRequest interface which is used to return all the cookies from the browser.

Create Cookies

To create cookies you need to use Cookie class of javax.servlet.http package.

Syntax

Cookie c=new Cookie(name, value);
// here name and value are string type

Add Cookies

To add a cookie to the response object, we use addCookie() mehtod.

Syntax

Cookie c=new Cookie();     //creating cookie object  
response.addCookie(c1); //adding cookie in the response

Read Cookies for browser

To read Cookies from browser to a servlet, we need to call getCookies methods given by request object and it returns an array type of cookie class.

Syntax

response.addCookie(c1);
Cookie c[]=request.getCookie();

Advantage of Cookie

  • Simplest technique of maintaining the state.
  • Cookie are maintained at client side so they do not give any burden to server.
  • All server side technology and all web server, application servers support cookies.
  • Presistent cookies can remember client data during session and after session with expiry time.

Limitation of Coockie

  • It will not work if cookie is disabled from the browser.
  • Cookies are text files, It does not provides security. Any one can change this file.
  • With coockies need client support that means if client disable the coockies then it does not store the client location.
  • Cookies can not store java objects as values, they only store text or string.

Example of session tracking by using Cookies

index.html

<form action="servlet1">
Name:<input type="text" name="userName"/> <br/>
<input type="submit" value="continue"/>
</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='continue'>");  
    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>  

Session Tracking in Servlet Servlet Hidden Form

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements