SlideShare a Scribd company logo
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.
SESSION TRACKING
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","Sam");
//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>
<servlet-name>s2</servlet-name>
<servlet-
class>SecondServlet</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Hidden Form Field
In case of Hidden Form Field a hidden (invisible)
textfield is used for maintaining the state of an user.
In such case, we store the information in the hidden
field and get it from another servlet.
This approach is better if we have to submit form in all
the pages and we don't want to depend on the browser.
Hidden Form Field
Application of hidden form field
It is widely used in comment form of a website.
In such case, we store page id or page name in the hidden
field so that each page can be uniquely identified
Advantage of Hidden Form Field
It will always work whether cookie is disabled or not.
Hidden Form Field
Disadvantage of Hidden Form Field:
•It is maintained at server side.
•Extra form submission is required on each pages.
•Only textual information can be used.
Hidden Form Field
URL Rewriting
•In URL rewriting, we append a token or identifier to
the URL of the next Servlet or the next resource.
•We can send parameter name/value pairs using the
following format:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal =
sign, a parameter name/value pair is separated from
another parameter using the ampersand (&).
URL Rewriting
When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server.
URL Rewriting
Advantage of URL Rewriting
It will always work whether cookie is disabled or not
(browser independent).
Extra form submission is not required on each pages.
Disadvantage of URL Rewriting
It will work only with links.
It can send Only text information.
SessionTrackServlets.pptx
SessionTrackServlets.pptx
SessionTrackServlets.pptx

More Related Content

Similar to SessionTrackServlets.pptx

Jsp session tracking
Jsp   session trackingJsp   session tracking
Jsp session tracking
rvarshneyp
 
self des session_T_M
self des session_T_Mself des session_T_M
self des session_T_M
Dayasagar Kadam
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
priya Nithya
 
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx
ssuser4a97d3
 
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.
 
Advance java session 7
Advance java session 7Advance java session 7
Advance java session 7
Smita B Kumar
 
Java EE 8 security and JSON binding API
Java EE 8 security and JSON binding APIJava EE 8 security and JSON binding API
Java EE 8 security and JSON binding API
Alex Theedom
 
Session tracking In Java
Session tracking In JavaSession tracking In Java
Session tracking In Java
honeyvachharajani
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
Programmer Blog
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.ppt
Jayaprasanna4
 
Manish
ManishManish
Manish
Manish Jain
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
Arumugam90
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2
Matt Raible
 
Sessions n cookies
Sessions n cookiesSessions n cookies
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
Tanmoy Barman
 
Session - 1 Forms and Session management.pptx
Session - 1 Forms and Session management.pptxSession - 1 Forms and Session management.pptx
Session - 1 Forms and Session management.pptx
imjdabhinawpandey
 
Cookies in servlet
Cookies in servletCookies in servlet
Cookies in servlet
chauhankapil
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
vantinhkhuc
 
Struts2 notes
Struts2 notesStruts2 notes
Struts2 notes
Rajiv Gupta
 

Similar to SessionTrackServlets.pptx (20)

Jsp session tracking
Jsp   session trackingJsp   session tracking
Jsp session tracking
 
self des session_T_M
self des session_T_Mself des session_T_M
self des session_T_M
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
 
19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx19_JavaScript - Storage_Cookies-tutorial .pptx
19_JavaScript - Storage_Cookies-tutorial .pptx
 
Authentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptxAuthentication in Svelte using cookies.pptx
Authentication in Svelte using cookies.pptx
 
Advance java session 7
Advance java session 7Advance java session 7
Advance java session 7
 
Java EE 8 security and JSON binding API
Java EE 8 security and JSON binding APIJava EE 8 security and JSON binding API
Java EE 8 security and JSON binding API
 
Session tracking In Java
Session tracking In JavaSession tracking In Java
Session tracking In Java
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Php ssession - cookies -introduction
Php ssession - cookies -introductionPhp ssession - cookies -introduction
Php ssession - cookies -introduction
 
session and cookies.ppt
session and cookies.pptsession and cookies.ppt
session and cookies.ppt
 
Manish
ManishManish
Manish
 
Java Servlets.pdf
Java Servlets.pdfJava Servlets.pdf
Java Servlets.pdf
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2
 
Sessions n cookies
Sessions n cookiesSessions n cookies
Sessions n cookies
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Session - 1 Forms and Session management.pptx
Session - 1 Forms and Session management.pptxSession - 1 Forms and Session management.pptx
Session - 1 Forms and Session management.pptx
 
Cookies in servlet
Cookies in servletCookies in servlet
Cookies in servlet
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
 
Struts2 notes
Struts2 notesStruts2 notes
Struts2 notes
 

Recently uploaded

How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
adhitya5119
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
PECB
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Excellence Foundation for South Sudan
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 

Recently uploaded (20)

How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
Advanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docxAdvanced Java[Extra Concepts, Not Difficult].docx
Advanced Java[Extra Concepts, Not Difficult].docx
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
Your Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective UpskillingYour Skill Boost Masterclass: Strategies for Effective Upskilling
Your Skill Boost Masterclass: Strategies for Effective Upskilling
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 

SessionTrackServlets.pptx

  • 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. SESSION TRACKING
  • 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","Sam"); //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);} } }
  • 20. Hidden Form Field In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user. In such case, we store the information in the hidden field and get it from another servlet. This approach is better if we have to submit form in all the pages and we don't want to depend on the browser.
  • 21. Hidden Form Field Application of hidden form field It is widely used in comment form of a website. In such case, we store page id or page name in the hidden field so that each page can be uniquely identified Advantage of Hidden Form Field It will always work whether cookie is disabled or not.
  • 22. Hidden Form Field Disadvantage of Hidden Form Field: •It is maintained at server side. •Extra form submission is required on each pages. •Only textual information can be used.
  • 24. URL Rewriting •In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. •We can send parameter name/value pairs using the following format: url?name1=value1&name2=value2&?? A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand (&).
  • 25. URL Rewriting When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server.
  • 26. URL Rewriting Advantage of URL Rewriting It will always work whether cookie is disabled or not (browser independent). Extra form submission is not required on each pages. Disadvantage of URL Rewriting It will work only with links. It can send Only text information.