SlideShare a Scribd company logo
2
Most read
3
Most read
5
Most read
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

PPT
Active Server Page(ASP)
PPT
Cookies in servlet
PPTX
Sessions in php
PDF
Adv java unit 4 M.Sc CS.pdf
PPTX
Java/Servlet/JSP/JDBC
PPTX
PPTX
PPTX
Server Side Programming
Active Server Page(ASP)
Cookies in servlet
Sessions in php
Adv java unit 4 M.Sc CS.pdf
Java/Servlet/JSP/JDBC
Server Side Programming

What's hot (20)

PPTX
Jdbc ppt
PPTX
HTTP request and response
PPS
Java Exception handling
PPT
Introduction to Javascript
PPTX
constructors in java ppt
PPTX
Javascript operators
PPTX
Classes objects in java
PPTX
Servlets
PPS
Jdbc architecture and driver types ppt
PPTX
PHP Cookies and Sessions
PPT
SQLITE Android
PDF
Java I/o streams
PPT
Java Servlets
PPTX
Java Server Pages(jsp)
PPTX
Java RMI
PPTX
Ajax
PPTX
Session tracking In Java
PPTX
Java Server Pages
PDF
Arrays in Java
PPTX
Event handling
Jdbc ppt
HTTP request and response
Java Exception handling
Introduction to Javascript
constructors in java ppt
Javascript operators
Classes objects in java
Servlets
Jdbc architecture and driver types ppt
PHP Cookies and Sessions
SQLITE Android
Java I/o streams
Java Servlets
Java Server Pages(jsp)
Java RMI
Ajax
Session tracking In Java
Java Server Pages
Arrays in Java
Event handling
Ad

Similar to Session tracking in servlets (20)

PPTX
SessionTrackServlets.pptx
PPTX
Servlet session 10
PPTX
Enterprise java unit-2_chapter-2
PDF
07 cookies
PPTX
Using cookies and sessions
PPTX
IMPORTANT SESSION TRACKING TECHNIQUES.pptx
PPTX
COOKIES.pptx
PPTX
Advance java session 7
PPTX
Cookies in servlets.ppt
PDF
Servlet sessions
PPTX
Cookies
PPTX
Cookies
PPT
PPT
session and cookies.ppt
PPTX
Session 32 - Session Management using Cookies
PPTX
java Cookies
PPTX
Advance Java
PPSX
Sessions and cookies
PPTX
Enterprise java unit-2_chapter-3
PPTX
Cookies
SessionTrackServlets.pptx
Servlet session 10
Enterprise java unit-2_chapter-2
07 cookies
Using cookies and sessions
IMPORTANT SESSION TRACKING TECHNIQUES.pptx
COOKIES.pptx
Advance java session 7
Cookies in servlets.ppt
Servlet sessions
Cookies
Cookies
session and cookies.ppt
Session 32 - Session Management using Cookies
java Cookies
Advance Java
Sessions and cookies
Enterprise java unit-2_chapter-3
Cookies
Ad

More from vishal choudhary (20)

PPTX
mobile application using automatin using node ja java on
PPTX
mobile development using node js and java
PPTX
Pixel to Percentage conversion Convert left and right padding of a div to per...
PPTX
esponsive web design means that your website (
PPTX
function in php using like three type of function
PPTX
data base connectivity in php using msql database
PPTX
software evelopment life cycle model and example of water fall model
PPTX
software Engineering lecture on development life cycle
PPTX
strings in php how to use different data types in string
PPTX
OPEN SOURCE WEB APPLICATION DEVELOPMENT question
PPTX
web performnace optimization using css minification
PPTX
web performance optimization using style
PPTX
Data types and variables in php for writing and databse
PPTX
Data types and variables in php for writing
PPTX
Data types and variables in php for writing
PPTX
sofwtare standard for test plan it execution
PPTX
Software test policy and test plan in development
PPTX
function in php like control loop and its uses
PPTX
introduction to php and its uses in daily
PPTX
data type in php and its introduction to use
mobile application using automatin using node ja java on
mobile development using node js and java
Pixel to Percentage conversion Convert left and right padding of a div to per...
esponsive web design means that your website (
function in php using like three type of function
data base connectivity in php using msql database
software evelopment life cycle model and example of water fall model
software Engineering lecture on development life cycle
strings in php how to use different data types in string
OPEN SOURCE WEB APPLICATION DEVELOPMENT question
web performnace optimization using css minification
web performance optimization using style
Data types and variables in php for writing and databse
Data types and variables in php for writing
Data types and variables in php for writing
sofwtare standard for test plan it execution
Software test policy and test plan in development
function in php like control loop and its uses
introduction to php and its uses in daily
data type in php and its introduction to use

Recently uploaded (20)

PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Complications of Minimal Access Surgery at WLH
PDF
Sports Quiz easy sports quiz sports quiz
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Cell Structure & Organelles in detailed.
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Classroom Observation Tools for Teachers
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
Pharma ospi slides which help in ospi learning
PDF
Basic Mud Logging Guide for educational purpose
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
Final Presentation General Medicine 03-08-2024.pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Complications of Minimal Access Surgery at WLH
Sports Quiz easy sports quiz sports quiz
TR - Agricultural Crops Production NC III.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Cell Structure & Organelles in detailed.
2.FourierTransform-ShortQuestionswithAnswers.pdf
Classroom Observation Tools for Teachers
Microbial diseases, their pathogenesis and prophylaxis
Microbial disease of the cardiovascular and lymphatic systems
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
FourierSeries-QuestionsWithAnswers(Part-A).pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Pharma ospi slides which help in ospi learning
Basic Mud Logging Guide for educational purpose
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPH.pptx obstetrics and gynecology in nursing
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
Final Presentation General Medicine 03-08-2024.pptx

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