SlideShare a Scribd company logo
1 of 19
Exp:Write a program in servlet for
session tracking using cookies
Session Tracking in Servlets
 Session simply means a particular interval of
time.
 Session Tracking is a way to maintain state
(data) of an user. It is also known as session
management in servlet.
 Http protocol is a stateless so we need to
maintain state using session tracking techniques.
Each time user requests to the server, server
treats the request as the new request. So we
need to maintain the state of an user to recognize
to particular user.
HTTP is stateless that means each request is
considered as the new request. It is shown in
the figure given below:
Why use Session Tracking?
 To recognize the user It is used to recognize the
particular user.
Session Tracking Techniques
There are four techniques used in Session tracking:
 Cookies
 Hidden Form Field
 URL Rewriting
 HttpSession
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 and domain
qualifiers, a maximum age, and a version
number.
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. 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 Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
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 session . It is not removed
each time when user closes the browser. It is
removed only if user logout or signout.
 Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the
browser.
2. Only textual information can be set in Cookie
object.
Cookie class
 javax.servlet.http.Cookie class 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 FoR 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.
How to create Cookie?
 Cookie ck=new Cookie("user","sonoo jaiswal"
);//creating cookie object
 response.addCookie(ck);//adding cookie in th
e response
How to 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 re
sponse
How to get Cookies?
 Cookie ck[]=request.getCookies();
 for(int i=0;i<ck.length;i++){
 out.print("<br>"+ck[i].getName()+" "+ck[i].get
Value());//printing name and value of cookie
}
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 session
corresponds to the particular user. So if you access it from too many
browsers with different values, you will get the different value.
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 Htt
pServlet {
public void doPost(HttpServletRequ
est request, HttpServletResponse res
ponse){
try{
response.setContentType("text/htm
l");
PrintWriter out = response.getWrite
r();
String n=request.getParameter("us
erName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//
creating cookie object
response.addCookie(ck);//adding c
ookie in the response
//creating submit button
out.print("<form action='servlet2'>")
;
out.print("<input type='submit' valu
e='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>

More Related Content

What's hot

Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state managementpriya Nithya
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectJadson Santos
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)Manisha Keim
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)Partnered Health
 
L21 io streams
L21 io streamsL21 io streams
L21 io streamsteach4uin
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web ApplicationRishi Kothari
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 

What's hot (20)

Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Js ppt
Js pptJs ppt
Js ppt
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
 
Introduction to angular with a simple but complete project
Introduction to angular with a simple but complete projectIntroduction to angular with a simple but complete project
Introduction to angular with a simple but complete project
 
Simple object access protocol(soap )
Simple object access protocol(soap )Simple object access protocol(soap )
Simple object access protocol(soap )
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Javascript
JavascriptJavascript
Javascript
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
L21 io streams
L21 io streamsL21 io streams
L21 io streams
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Developing an ASP.NET Web Application
Developing an ASP.NET Web ApplicationDeveloping an ASP.NET Web Application
Developing an ASP.NET Web Application
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Java script basics
Java script basicsJava script basics
Java script basics
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 

Similar to Session tracking in servlets

SessionTrackServlets.pptx
SessionTrackServlets.pptxSessionTrackServlets.pptx
SessionTrackServlets.pptxRanjeet Reddy
 
Cookies in servlet
Cookies in servletCookies in servlet
Cookies in servletchauhankapil
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxKnoldus Inc.
 
Using cookies and sessions
Using cookies and sessionsUsing cookies and sessions
Using cookies and sessionsNuha Noor
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptxITNet
 
Enterprise java unit-2_chapter-2
Enterprise  java unit-2_chapter-2Enterprise  java unit-2_chapter-2
Enterprise java unit-2_chapter-2sandeep54552
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introductionProgrammer Blog
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionMazenetsolution
 
Cookies in Angular | Install CookiesService
Cookies in Angular | Install CookiesServiceCookies in Angular | Install CookiesService
Cookies in Angular | Install CookiesServicePradeep Kumar
 
Session And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaSession And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaJainamParikh3
 
Maker Checker -Incorporating Multiple Roles in Single SilkPerformer script
Maker Checker -Incorporating Multiple Roles in Single SilkPerformer scriptMaker Checker -Incorporating Multiple Roles in Single SilkPerformer script
Maker Checker -Incorporating Multiple Roles in Single SilkPerformer scriptSwarnkar Rajesh
 
Enterprise java unit-2_chapter-3
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3sandeep54552
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSDegu8
 
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptxssuser4a97d3
 
Cookie & Session In ASP.NET
Cookie & Session In ASP.NETCookie & Session In ASP.NET
Cookie & Session In ASP.NETShingalaKrupa
 

Similar to Session tracking in servlets (20)

Servlet session 10
Servlet   session 10Servlet   session 10
Servlet session 10
 
SessionTrackServlets.pptx
SessionTrackServlets.pptxSessionTrackServlets.pptx
SessionTrackServlets.pptx
 
Cookies in servlet
Cookies in servletCookies in servlet
Cookies in servlet
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
 
Session tracking In Java
Session tracking In JavaSession tracking In Java
Session tracking In Java
 
Using cookies and sessions
Using cookies and sessionsUsing cookies and sessions
Using cookies and sessions
 
Session,cookies
Session,cookiesSession,cookies
Session,cookies
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptx
 
Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
 
Enterprise java unit-2_chapter-2
Enterprise  java unit-2_chapter-2Enterprise  java unit-2_chapter-2
Enterprise java unit-2_chapter-2
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
 
Cookies in Angular | Install CookiesService
Cookies in Angular | Install CookiesServiceCookies in Angular | Install CookiesService
Cookies in Angular | Install CookiesService
 
Session And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaSession And Cookies In Servlets - Java
Session And Cookies In Servlets - Java
 
Ecom2
Ecom2Ecom2
Ecom2
 
Maker Checker -Incorporating Multiple Roles in Single SilkPerformer script
Maker Checker -Incorporating Multiple Roles in Single SilkPerformer scriptMaker Checker -Incorporating Multiple Roles in Single SilkPerformer script
Maker Checker -Incorporating Multiple Roles in Single SilkPerformer script
 
Enterprise java unit-2_chapter-3
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3
 
PHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONSPHP COOKIES AND SESSIONS
PHP COOKIES AND SESSIONS
 
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx
 
Cookie & Session In ASP.NET
Cookie & Session In ASP.NETCookie & Session In ASP.NET
Cookie & Session In ASP.NET
 

More from vishal choudhary (20)

SE-Lecture1.ppt
SE-Lecture1.pptSE-Lecture1.ppt
SE-Lecture1.ppt
 
SE-Testing.ppt
SE-Testing.pptSE-Testing.ppt
SE-Testing.ppt
 
SE-CyclomaticComplexityand Testing.ppt
SE-CyclomaticComplexityand Testing.pptSE-CyclomaticComplexityand Testing.ppt
SE-CyclomaticComplexityand Testing.ppt
 
SE-Lecture-7.pptx
SE-Lecture-7.pptxSE-Lecture-7.pptx
SE-Lecture-7.pptx
 
Se-Lecture-6.ppt
Se-Lecture-6.pptSe-Lecture-6.ppt
Se-Lecture-6.ppt
 
SE-Lecture-5.pptx
SE-Lecture-5.pptxSE-Lecture-5.pptx
SE-Lecture-5.pptx
 
XML.pptx
XML.pptxXML.pptx
XML.pptx
 
SE-Lecture-8.pptx
SE-Lecture-8.pptxSE-Lecture-8.pptx
SE-Lecture-8.pptx
 
SE-coupling and cohesion.ppt
SE-coupling and cohesion.pptSE-coupling and cohesion.ppt
SE-coupling and cohesion.ppt
 
SE-Lecture-2.pptx
SE-Lecture-2.pptxSE-Lecture-2.pptx
SE-Lecture-2.pptx
 
SE-software design.ppt
SE-software design.pptSE-software design.ppt
SE-software design.ppt
 
SE1.ppt
SE1.pptSE1.ppt
SE1.ppt
 
SE-Lecture-4.pptx
SE-Lecture-4.pptxSE-Lecture-4.pptx
SE-Lecture-4.pptx
 
SE-Lecture=3.pptx
SE-Lecture=3.pptxSE-Lecture=3.pptx
SE-Lecture=3.pptx
 
Multimedia-Lecture-Animation.pptx
Multimedia-Lecture-Animation.pptxMultimedia-Lecture-Animation.pptx
Multimedia-Lecture-Animation.pptx
 
MultimediaLecture5.pptx
MultimediaLecture5.pptxMultimediaLecture5.pptx
MultimediaLecture5.pptx
 
Multimedia-Lecture-7.pptx
Multimedia-Lecture-7.pptxMultimedia-Lecture-7.pptx
Multimedia-Lecture-7.pptx
 
MultiMedia-Lecture-4.pptx
MultiMedia-Lecture-4.pptxMultiMedia-Lecture-4.pptx
MultiMedia-Lecture-4.pptx
 
Multimedia-Lecture-6.pptx
Multimedia-Lecture-6.pptxMultimedia-Lecture-6.pptx
Multimedia-Lecture-6.pptx
 
Multimedia-Lecture-3.pptx
Multimedia-Lecture-3.pptxMultimedia-Lecture-3.pptx
Multimedia-Lecture-3.pptx
 

Recently uploaded

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxEsquimalt MFRC
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfstareducators107
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17Celine George
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactisticshameyhk98
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxPooja Bhuva
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 

Recently uploaded (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 

Session tracking in servlets

  • 1. Exp:Write a program in servlet for session tracking using cookies Session Tracking in Servlets
  • 2.  Session simply means a particular interval of time.  Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet.  Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user.
  • 3. HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below:
  • 4. Why use Session Tracking?  To recognize the user It is used to recognize the particular user. Session Tracking Techniques There are four techniques used in Session tracking:  Cookies  Hidden Form Field  URL Rewriting  HttpSession
  • 5. 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 and domain qualifiers, a maximum age, and a version number.
  • 6. 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. 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.
  • 7. Types of Cookie There are 2 types of cookies in servlets. 1. Non-persistent cookie 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 session . It is not removed each time when user closes the browser. It is removed only if user logout or signout.
  • 8.  Advantage of Cookies 1. Simplest technique of maintaining the state. 2. Cookies are maintained at client side. Disadvantage of Cookies 1. It will not work if cookie is disabled from the browser. 2. Only textual information can be set in Cookie object.
  • 9. Cookie class  javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.
  • 10. Constructor of Cookie class Constructor Description Cookie() constructs a cookie. Cookie(String name, String value) constructs a cookie with a specified name and value.
  • 11. Useful Methods FoR 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.
  • 12. How to create Cookie?  Cookie ck=new Cookie("user","sonoo jaiswal" );//creating cookie object  response.addCookie(ck);//adding cookie in th e response
  • 13. How to 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 re sponse
  • 14. How to get Cookies?  Cookie ck[]=request.getCookies();  for(int i=0;i<ck.length;i++){  out.print("<br>"+ck[i].getName()+" "+ck[i].get Value());//printing name and value of cookie }
  • 15. 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 session corresponds to the particular user. So if you access it from too many browsers with different values, you will get the different value.
  • 16. index.html  <form action="servlet1" method="post">  Name:<input type="text" name="userName"/><br/ >  <input type="submit" value="go"/>  </form>
  • 17. FirstServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class FirstServlet extends Htt pServlet { public void doPost(HttpServletRequ est request, HttpServletResponse res ponse){ try{ response.setContentType("text/htm l"); PrintWriter out = response.getWrite r(); String n=request.getParameter("us erName"); out.print("Welcome "+n); Cookie ck=new Cookie("uname",n);// creating cookie object response.addCookie(ck);//adding c ookie in the response //creating submit button out.print("<form action='servlet2'>") ; out.print("<input type='submit' valu e='go'>"); out.print("</form>"); out.close(); }catch(Exception e){System.out. println(e);} } }
  • 18. 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);} } }