SlideShare a Scribd company logo
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>
Ad

More Related Content

What's hot (20)

Java beans
Java beansJava beans
Java beans
Rajkiran Mummadi
 
PHP Cookies and Sessions
PHP Cookies and SessionsPHP Cookies and Sessions
PHP Cookies and Sessions
Nisa Soomro
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
Nisa Soomro
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
Elizabeth alexander
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
Vikas Jagtap
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
Zeeshan Ahmed
 
Js ppt
Js pptJs ppt
Js ppt
Rakhi Thota
 
Angular Directives
Angular DirectivesAngular Directives
Angular Directives
Malla Reddy University
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
Manisha Keim
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation Technique
Morshedul Arefin
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
priya Nithya
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
Sourabh Sahu
 
Notification android
Notification androidNotification android
Notification android
ksheerod shri toshniwal
 
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
javascript objects
javascript objectsjavascript objects
javascript objects
Vijay Kalyan
 
Ajax ppt
Ajax pptAjax ppt
Ajax ppt
OECLIB Odisha Electronics Control Library
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
sandeep54552
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
shanmuga rajan
 

Similar to Session tracking in servlets (20)

Servlet session 10
Servlet   session 10Servlet   session 10
Servlet session 10
Anuj Singh Rajput
 
SessionTrackServlets.pptx
SessionTrackServlets.pptxSessionTrackServlets.pptx
SessionTrackServlets.pptx
Ranjeet Reddy
 
Cookies in servlet
Cookies in servletCookies in servlet
Cookies in servlet
chauhankapil
 
IMPORTANT SESSION TRACKING TECHNIQUES.pptx
IMPORTANT SESSION TRACKING TECHNIQUES.pptxIMPORTANT SESSION TRACKING TECHNIQUES.pptx
IMPORTANT SESSION TRACKING TECHNIQUES.pptx
yvtinsane
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
Knoldus Inc.
 
Session tracking In Java
Session tracking In JavaSession tracking In Java
Session tracking In Java
honeyvachharajani
 
Using cookies and sessions
Using cookies and sessionsUsing cookies and sessions
Using cookies and sessions
Nuha Noor
 
WORKING WITH IN COOKIES JAVA SEMINAR.pptx
WORKING WITH IN COOKIES JAVA SEMINAR.pptxWORKING WITH IN COOKIES JAVA SEMINAR.pptx
WORKING WITH IN COOKIES JAVA SEMINAR.pptx
nandhini342004
 
Session,cookies
Session,cookiesSession,cookies
Session,cookies
rkmourya511
 
Working with in cookies java seminar.pptx
Working with in cookies java seminar.pptxWorking with in cookies java seminar.pptx
Working with in cookies java seminar.pptx
nandhini342004
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptx
ITNet
 
Sessions and cookies
Sessions and cookiesSessions and cookies
Sessions and cookies
www.netgains.org
 
Enterprise java unit-2_chapter-2
Enterprise  java unit-2_chapter-2Enterprise  java unit-2_chapter-2
Enterprise java unit-2_chapter-2
sandeep54552
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
Programmer Blog
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
Mazenetsolution
 
Cookies in Angular | Install CookiesService
Cookies in Angular | Install CookiesServiceCookies in Angular | Install CookiesService
Cookies in Angular | Install CookiesService
Pradeep Kumar
 
Session And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaSession And Cookies In Servlets - Java
Session And Cookies In Servlets - Java
JainamParikh3
 
Ecom2
Ecom2Ecom2
Ecom2
Santosh Pandey
 
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
Swarnkar Rajesh
 
Enterprise java unit-2_chapter-3
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3
sandeep54552
 
SessionTrackServlets.pptx
SessionTrackServlets.pptxSessionTrackServlets.pptx
SessionTrackServlets.pptx
Ranjeet Reddy
 
Cookies in servlet
Cookies in servletCookies in servlet
Cookies in servlet
chauhankapil
 
IMPORTANT SESSION TRACKING TECHNIQUES.pptx
IMPORTANT SESSION TRACKING TECHNIQUES.pptxIMPORTANT SESSION TRACKING TECHNIQUES.pptx
IMPORTANT SESSION TRACKING TECHNIQUES.pptx
yvtinsane
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
Knoldus Inc.
 
Using cookies and sessions
Using cookies and sessionsUsing cookies and sessions
Using cookies and sessions
Nuha Noor
 
WORKING WITH IN COOKIES JAVA SEMINAR.pptx
WORKING WITH IN COOKIES JAVA SEMINAR.pptxWORKING WITH IN COOKIES JAVA SEMINAR.pptx
WORKING WITH IN COOKIES JAVA SEMINAR.pptx
nandhini342004
 
Working with in cookies java seminar.pptx
Working with in cookies java seminar.pptxWorking with in cookies java seminar.pptx
Working with in cookies java seminar.pptx
nandhini342004
 
lecture 12.pptx
lecture 12.pptxlecture 12.pptx
lecture 12.pptx
ITNet
 
Enterprise java unit-2_chapter-2
Enterprise  java unit-2_chapter-2Enterprise  java unit-2_chapter-2
Enterprise java unit-2_chapter-2
sandeep54552
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
Programmer Blog
 
Java - Servlet - Mazenet Solution
Java - Servlet - Mazenet SolutionJava - Servlet - Mazenet Solution
Java - Servlet - Mazenet Solution
Mazenetsolution
 
Cookies in Angular | Install CookiesService
Cookies in Angular | Install CookiesServiceCookies in Angular | Install CookiesService
Cookies in Angular | Install CookiesService
Pradeep Kumar
 
Session And Cookies In Servlets - Java
Session And Cookies In Servlets - JavaSession And Cookies In Servlets - Java
Session And Cookies In Servlets - Java
JainamParikh3
 
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
Swarnkar Rajesh
 
Enterprise java unit-2_chapter-3
Enterprise  java unit-2_chapter-3Enterprise  java unit-2_chapter-3
Enterprise java unit-2_chapter-3
sandeep54552
 
Ad

More from vishal choudhary (20)

function in php using like three type of function
function in php using  like three type of functionfunction in php using  like three type of function
function in php using like three type of function
vishal choudhary
 
data base connectivity in php using msql database
data base connectivity in php using msql databasedata base connectivity in php using msql database
data base connectivity in php using msql database
vishal choudhary
 
software evelopment life cycle model and example of water fall model
software evelopment life cycle model and example of water fall modelsoftware evelopment life cycle model and example of water fall model
software evelopment life cycle model and example of water fall model
vishal choudhary
 
software Engineering lecture on development life cycle
software Engineering lecture on development life cyclesoftware Engineering lecture on development life cycle
software Engineering lecture on development life cycle
vishal choudhary
 
strings in php how to use different data types in string
strings in php how to use different data types in stringstrings in php how to use different data types in string
strings in php how to use different data types in string
vishal choudhary
 
OPEN SOURCE WEB APPLICATION DEVELOPMENT question
OPEN SOURCE WEB APPLICATION DEVELOPMENT  questionOPEN SOURCE WEB APPLICATION DEVELOPMENT  question
OPEN SOURCE WEB APPLICATION DEVELOPMENT question
vishal choudhary
 
web performnace optimization using css minification
web performnace optimization using css minificationweb performnace optimization using css minification
web performnace optimization using css minification
vishal choudhary
 
web performance optimization using style
web performance optimization using styleweb performance optimization using style
web performance optimization using style
vishal choudhary
 
Data types and variables in php for writing and databse
Data types and variables in php for writing  and databseData types and variables in php for writing  and databse
Data types and variables in php for writing and databse
vishal choudhary
 
Data types and variables in php for writing
Data types and variables in php for writingData types and variables in php for writing
Data types and variables in php for writing
vishal choudhary
 
Data types and variables in php for writing
Data types and variables in php for writingData types and variables in php for writing
Data types and variables in php for writing
vishal choudhary
 
sofwtare standard for test plan it execution
sofwtare standard for test plan it executionsofwtare standard for test plan it execution
sofwtare standard for test plan it execution
vishal choudhary
 
Software test policy and test plan in development
Software test policy and test plan in developmentSoftware test policy and test plan in development
Software test policy and test plan in development
vishal choudhary
 
function in php like control loop and its uses
function in php like control loop and its usesfunction in php like control loop and its uses
function in php like control loop and its uses
vishal choudhary
 
introduction to php and its uses in daily
introduction to php and its uses in dailyintroduction to php and its uses in daily
introduction to php and its uses in daily
vishal choudhary
 
data type in php and its introduction to use
data type in php and its introduction to usedata type in php and its introduction to use
data type in php and its introduction to use
vishal choudhary
 
PHP introduction how to create and start php
PHP introduction how to create and start phpPHP introduction how to create and start php
PHP introduction how to create and start php
vishal choudhary
 
SE-Lecture1.ppt
SE-Lecture1.pptSE-Lecture1.ppt
SE-Lecture1.ppt
vishal choudhary
 
SE-Testing.ppt
SE-Testing.pptSE-Testing.ppt
SE-Testing.ppt
vishal choudhary
 
SE-CyclomaticComplexityand Testing.ppt
SE-CyclomaticComplexityand Testing.pptSE-CyclomaticComplexityand Testing.ppt
SE-CyclomaticComplexityand Testing.ppt
vishal choudhary
 
function in php using like three type of function
function in php using  like three type of functionfunction in php using  like three type of function
function in php using like three type of function
vishal choudhary
 
data base connectivity in php using msql database
data base connectivity in php using msql databasedata base connectivity in php using msql database
data base connectivity in php using msql database
vishal choudhary
 
software evelopment life cycle model and example of water fall model
software evelopment life cycle model and example of water fall modelsoftware evelopment life cycle model and example of water fall model
software evelopment life cycle model and example of water fall model
vishal choudhary
 
software Engineering lecture on development life cycle
software Engineering lecture on development life cyclesoftware Engineering lecture on development life cycle
software Engineering lecture on development life cycle
vishal choudhary
 
strings in php how to use different data types in string
strings in php how to use different data types in stringstrings in php how to use different data types in string
strings in php how to use different data types in string
vishal choudhary
 
OPEN SOURCE WEB APPLICATION DEVELOPMENT question
OPEN SOURCE WEB APPLICATION DEVELOPMENT  questionOPEN SOURCE WEB APPLICATION DEVELOPMENT  question
OPEN SOURCE WEB APPLICATION DEVELOPMENT question
vishal choudhary
 
web performnace optimization using css minification
web performnace optimization using css minificationweb performnace optimization using css minification
web performnace optimization using css minification
vishal choudhary
 
web performance optimization using style
web performance optimization using styleweb performance optimization using style
web performance optimization using style
vishal choudhary
 
Data types and variables in php for writing and databse
Data types and variables in php for writing  and databseData types and variables in php for writing  and databse
Data types and variables in php for writing and databse
vishal choudhary
 
Data types and variables in php for writing
Data types and variables in php for writingData types and variables in php for writing
Data types and variables in php for writing
vishal choudhary
 
Data types and variables in php for writing
Data types and variables in php for writingData types and variables in php for writing
Data types and variables in php for writing
vishal choudhary
 
sofwtare standard for test plan it execution
sofwtare standard for test plan it executionsofwtare standard for test plan it execution
sofwtare standard for test plan it execution
vishal choudhary
 
Software test policy and test plan in development
Software test policy and test plan in developmentSoftware test policy and test plan in development
Software test policy and test plan in development
vishal choudhary
 
function in php like control loop and its uses
function in php like control loop and its usesfunction in php like control loop and its uses
function in php like control loop and its uses
vishal choudhary
 
introduction to php and its uses in daily
introduction to php and its uses in dailyintroduction to php and its uses in daily
introduction to php and its uses in daily
vishal choudhary
 
data type in php and its introduction to use
data type in php and its introduction to usedata type in php and its introduction to use
data type in php and its introduction to use
vishal choudhary
 
PHP introduction how to create and start php
PHP introduction how to create and start phpPHP introduction how to create and start php
PHP introduction how to create and start php
vishal choudhary
 
SE-CyclomaticComplexityand Testing.ppt
SE-CyclomaticComplexityand Testing.pptSE-CyclomaticComplexityand Testing.ppt
SE-CyclomaticComplexityand Testing.ppt
vishal choudhary
 
Ad

Recently uploaded (20)

P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Open Access: Revamping Library Learning Resources.
Open Access: Revamping Library Learning Resources.Open Access: Revamping Library Learning Resources.
Open Access: Revamping Library Learning Resources.
Rishi Bankim Chandra Evening College, Naihati, North 24 Parganas, West Bengal, India
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Timber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptxTimber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptx
Tantish QS, UTM
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Envenomation---Clinical Toxicology. pptx
Envenomation---Clinical Toxicology. pptxEnvenomation---Clinical Toxicology. pptx
Envenomation---Clinical Toxicology. pptx
rekhapositivity
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Fundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic CommunicationsFundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic Communications
Jordan Williams
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Unit 5: Dividend Decisions and its theories
Unit 5: Dividend Decisions and its theoriesUnit 5: Dividend Decisions and its theories
Unit 5: Dividend Decisions and its theories
bharath321164
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Timber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptxTimber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptx
Tantish QS, UTM
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Envenomation---Clinical Toxicology. pptx
Envenomation---Clinical Toxicology. pptxEnvenomation---Clinical Toxicology. pptx
Envenomation---Clinical Toxicology. pptx
rekhapositivity
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Presentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem KayaPresentation of the MIPLM subject matter expert Erdem Kaya
Presentation of the MIPLM subject matter expert Erdem Kaya
MIPLM
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Fundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic CommunicationsFundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic Communications
Jordan Williams
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Unit 5: Dividend Decisions and its theories
Unit 5: Dividend Decisions and its theoriesUnit 5: Dividend Decisions and its theories
Unit 5: Dividend Decisions and its theories
bharath321164
 

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);} } }