SlideShare a Scribd company logo
Slide 1 of 30© People Strategists www.peoplestrategists.com
Working with Servlets
Slide 2 of 30© People Strategists www.peoplestrategists.com
Objectives
In this session, you will learn to:
Explore the ServletConfig interface
Explore the ServletContext interface
Implement ServletContext Inerface
Introduce session tracking
Implement session tracking
Slide 3 of 30© People Strategists www.peoplestrategists.com
The ServletConfig interface:
Is implemented by a Web container during the initialization of a
servlet to pass the configuration information to a servlet.
Is passed to the init()method of the servlet during initialization.
Can be used to pass initialization parameters to the servlets.
The initialization parameters are passed as name-value pairs.
For example, the connection URL can be passed as an initialization
parameter of the servlet.
Exploring the ServletConfig Interface
Slide 4 of 30© People Strategists www.peoplestrategists.com
The following table describes the various methods defined in the
ServletConfig interface:
Exploring the ServletConfig Interface (Contd.)
Method Description
String getInitParameter(String
param)
It returns a String object containing the
value of the initialization parameters.
Enumeration<String>
getInitParameterNames()
It returns the names of all the initialization
parameters as an enumeration of String
objects.
ServletContext getServletContext() It returns the ServletContext object for
the servlet in which the caller is executing.
String getServletName() It returns a String object containing the
name of the servlet instance.
Slide 5 of 30© People Strategists www.peoplestrategists.com
The ServletContext provides the environmental information to
the servlets in which they are running.
Each Web application consists of only one ServletContext
object.
A ServletContext object is also known as a Web context.
The Web container creates an object of ServletContext at time
of deploying the project.
Following figure shows the creation of ServletContext object.
Exploring the ServletContext Interface
ServletContext Object Creation
Slide 6 of 30© People Strategists www.peoplestrategists.com
The following table describes the various methods defined in the
ServletContext interface:
Exploring the ServletContext Interface (Contd.)
Method Description
public void setAttribute(String,
Object)
Binds the object with a name and stores
the name/value pair as an attribute of the
ServletContext object. If an attribute
already exists, this method replaces the
existing attribute.
public Object getAttribute(String
attrname)
Returns the object stored in the
ServletContext object with the name
passed as a parameter.
public Enumeration
getAttributeNames()
Returns an enumeration of the String
object that contains names of all the
context attributes.
public String
getInitParameter(String pname)
Returns the value of the initialization
parameter with the name passed as a
parameter.
public Enumeration
getInitParameterNames()
Returns an enumeration of String object
that contains names of all the initialization
parameters.
Slide 7 of 30© People Strategists www.peoplestrategists.com
Usage of the ServletContext interface:
The ServletContext object provides an interface between the
container and servlet.
It can be used to get configuration information from the web.xml
file.
It can be used to set, get or remove attribute from the web.xml file.
It can be used to provide inter-application communication.
You can access ServletContext object using the
getServletContext method of:
The ServletConfig interface,
The GenericServlet class
The HttpServletRequest interface
Exploring the ServletContext Interface (Contd.)
Slide 8 of 30© People Strategists www.peoplestrategists.com
Accessing ServletContext object using the
getServletContext method of the ServletConfig interface:
You can use the following code snippet to get the ServletContext
object:
In the preceding code snippet,
 The getServletConfig method returns the object of
ServletConfig.
 Thereafter, the conf object calls getServletContext that returns the
ServletContext object.
Implementing the ServletContext Interface
ServletConfig conf = getServletConfig();
ServletContext context = conf.getServletContext();
Slide 9 of 30© People Strategists www.peoplestrategists.com
Consider a scenario where you need to develop a Web application
that stores the email and name of user in web.xml file. In
addition, you need to access those parameters using
ServletContext and display them, as shown in the following
figure.
Activity: Implementing the ServletContext Interface
The Expected Output
Slide 10 of 30© People Strategists www.peoplestrategists.com
Accessing ServletContext object using the
getServletContext method of the GenericServlet class:
In general, every servlet class extends HttpServlet, which is a sub
class of GenericServlet.
Use the following code snippet to access the ServletContext
object:
In the preceding code snippet, the getServletContext method
returns the ServletContext object.
Implementing the ServletContext Interface (Contd.)
ServletContext context = getServletContext();
Slide 11 of 30© People Strategists www.peoplestrategists.com
Consider a scenario where you need to develop a Web application
that fulfills the following requirements:
It should provide a user interface to accept the credentials, as shown
in the following figure.
It should validate the entered details with value stored in the
web.xml file.
Activity: Implementing ServletContext Using GenericServlet
The Expected Output
Slide 12 of 30© People Strategists www.peoplestrategists.com
It should display welcome message if the credentials are correct, as
shown in the following figure.
Activity: Implementing ServletContext Using GenericServlet (Contd.)
The Expected Output
Slide 13 of 30© People Strategists www.peoplestrategists.com
Accessing ServletContext object using the
getServletContext method of the HttpRequestServlet
interface:
You can use the following code snippet to access the
ServletContext object:
In the preceding code snippet, the req object calls the
getServletContext method that returns the ServletContext
object.
Implementing the ServletContext Interface (Contd.)
public void doGet/doPost(HttpServletRequest req,
HttpServletResponse res)
{
ServletContext ctx = req.getServletContext();
}
Slide 14 of 30© People Strategists www.peoplestrategists.com
Consider a scenario where you need to develop a Web application
that fulfills the following requirements:
It should provide a user interface to accept the customer details, as
shown in the following figure:
It should store the entered details to access database.
It should display a message “Details are saved.”
Activity: Implementing ServletContext Using HttpServletRequest
The Expected Output
Slide 15 of 30© People Strategists www.peoplestrategists.com
Session tracking is the process of maintaining information, or
state, about Web site visitors as they move from page to page.
The connection from a browser to a Web server occurs over the
stateless Hypertext Transfer Protocol (HTTP).
Therefore, the Web developer has to explicitly write code to
implement session tracking.
The mechanism to implement session tracking are:
HttpSession
Cookie
URL Rewriting
Introducing Session Tracking
Slide 16 of 30© People Strategists www.peoplestrategists.com
HttpSession:
It is an interface that provides methods to handle session tracking.
A session object is created on the application server, usually in a Java
servlet or a Java Server Page.
The object gets stored on the application server and a unique
identifier called a session ID is assigned to it.
The object and session ID are handled by a session manager on the
application server.
Each session ID assigned by the application server has zero or more
key/value pairs tied to it.
The values are objects that you place in the session.
Implementing Session Tracking
Slide 17 of 30© People Strategists www.peoplestrategists.com
The following table describes the various methods defined in the
HttpSession interface:
Implementing Session Tracking (Contd.)
Method Description
public void setAttribute(String
name, Object value)
Binds the object with a name and stores the
name/value pair as an attribute of the
HttpSession object. If an attribute already
exists, this method replaces the existing attribute.
public Object getAttribute(String
name)
Retrieves the String object specified in the
parameter, from the session object. If no object
is found for the specified attribute, the
getAttribute()method returns null.
public Enumeration
getAttributeNames()
Returns an Enumeration object that contains the
name of all the objects that are bound as
attributes to the session object.
public void
removeAttribute(String name)
Removes the object bound with the specified
name from this session.
public void invalidate() Invalidates this session and unbinds any objects
bound to it.
public Boolean isNew() Returns a Boolean with a value of true if the client
does not yet know about the session or if the
client chooses not to join the session
Slide 18 of 30© People Strategists www.peoplestrategists.com
To use HttpSession object, you need to:
Create and retrieve session object using the getSession method of
HttpServletRequest.
Following code snippet shows an example:
The getSession method is passed a boolean value.
The false value indicates that you want to retrieve an existing
session object.
The true value lets the session manager know that a session object
needs to be created if one does not already exist.
Implementing Session Tracking (Contd.)
HttpSession session = request.getSession(true);
Slide 19 of 30© People Strategists www.peoplestrategists.com
An object of HttpSession can find out that the session is new or
can remove one.
Following code snippet shows an example:
In the above code snippet, the existing session object gets
removed and a new session object is created.
Implementing Session Tracking (Contd.)
HttpSession session = request.getSession (true);
if (session.isNew() == false) {
session.invalidate();
session = request.getSession(true);
}
Slide 20 of 30© People Strategists www.peoplestrategists.com
You need to develop a Web application that allows users to buy
products online. The application should be based on the following
guidelines:
It should provide a login page, as sown in the following figure.
Activity: Implementing Session Tracking Using HttpSession
The Expected Output
Slide 21 of 30© People Strategists www.peoplestrategists.com
It should display a Web page to select brands of shirts, as sown in
the following figure.
Activity: Implementing Session Tracking Using HttpSession (Contd.)
The Expected Output
Slide 22 of 30© People Strategists www.peoplestrategists.com
It should display the bill based on the selection, as shown in the
following figure.
Activity: Implementing Session Tracking Using HttpSession (Contd.)
The Expected Output
Slide 23 of 30© People Strategists www.peoplestrategists.com
Cookie:
Is information that is stored as a name/value pair.
Is transmitted from the server to the browser.
Is a common way of session tracking.
Cookies can be used to tie specific visitors to information about
them on the server.
The Java servlet specification provides a simple cookie API that
allows you to write and retrieve cookies.
Following code snippet creates a Cookie object:
The Cookie object is valid for one hour.
The response object adds the cookie for later use.
Implementing Session Tracking (Contd.)
Cookie user = new Cookie("user","Jennifer");
user.setMaxAge(3600);
response.addCookie(user);
Slide 24 of 30© People Strategists www.peoplestrategists.com
Following code snippet retrieves the Cookie object:
The getCookies method retrieves the stored cookies.
The getName method returns the cookie name.
The getValue method returns the value stored in cookie.
Implementing Session Tracking (Contd.)
String user = "";
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals("user"))
user =cookies[i].getValue();
}
}
Slide 25 of 30© People Strategists www.peoplestrategists.com
You need to develop a Web application that accepts the name of a
user and writes it to cookie. For this, you need to create a user
interface, as shown in the following figure.
Activity: Implementing Session Tracking Using Cookie
The Expected Output
Slide 26 of 30© People Strategists www.peoplestrategists.com
In addition, you need to read the cookie value and display it, as
shown in the following figure.
Activity: Implementing Session Tracking Using Cookie (Contd.)
The Expected Output
Slide 27 of 30© People Strategists www.peoplestrategists.com
URL Rewriting:
is the lowest common denominator of session tracking.
Can be used for session tracking if client does not support cookies.
Involves adding data, a session ID, to the URL path that is
interpreted by the container to associate the request with a session.
In URL rewriting, users append a token or identifier to the URL of
the next Servlet or the next resource.
Implementing Session Tracking (Contd.)
Slide 28 of 30© People Strategists www.peoplestrategists.com
The HttpServletResponse interface provides following two
methods for URL Rewriting:
encodeURL(String):
 Encodes the specified URL by including the session ID in it.
 Returns the URL unchanged if encoding is not needed.
URLencodeRedirectURL(String):
 Encodes the specified URL for use in the sendRedirect method.
 Returns the URL unchanged if encoding is not needed.
 All URLs sent to the HttpServletResponse.sendRedirect
method should be run through this method. Otherwise, URL rewriting
cannot be used with browsers which do not support cookies.
Implementing Session Tracking (Contd.)
Slide 29 of 30© People Strategists www.peoplestrategists.com
Summary
In this session, you learned that:
ServletConfig is implemented by a Web container during the initialization
of a servlet to pass the configuration information to a servlet.
ServletContext provides the environmental information to the servlets in
which they are running.
Usage of the ServletContext interface are:
 It can be used to get configuration information from the web.xml file.
 It can be used to set, get or remove attribute from the web.xml file.
 It can be used to provide inter-application communication.
Session tracking is the process of maintaining information, or state, about
Web site visitors as they move from page to page.
The mechanism to implement session tracking are:
 HttpSession
 Cookie
 URL Rewriting
Slide 30 of 30© People Strategists www.peoplestrategists.com
Summary (Contd.)
HttpSession is an interface that provides methods to handle session
tracking.
Cookie is information that is stored as a name/value pair and is transmitted
from the server to the browser.
It Is a common way of session tracking.
URL Rewriting can be used for session tracking if client does not support
cookies.
It Involves adding data, a session ID, to the URL path that is interpreted by the
container to associate the request with a session.

More Related Content

PDF
JSP Technology II
PDF
Exploring Maven SVN GIT
PDF
Overview of JEE Technology
PDF
JSP Technology I
PDF
Spring Framework - III
PDF
Spring Framework-II
PDF
Hibernate III
PDF
Spring Framework -I
JSP Technology II
Exploring Maven SVN GIT
Overview of JEE Technology
JSP Technology I
Spring Framework - III
Spring Framework-II
Hibernate III
Spring Framework -I

What's hot (19)

PPT
Struts Introduction Course
PDF
Hibernate II
DOCX
TY.BSc.IT Java QB U3
DOCX
TY.BSc.IT Java QB U4
PDF
Hibernate I
DOCX
Struts notes
PDF
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
PPTX
Spring andspringboot training
PPT
Spring Core
PPT
JEE5 New Features
DOCX
TY.BSc.IT Java QB U1
PPT
Struts,Jsp,Servlet
PPT
Struts course material
PDF
Java Web Programming [8/9] : JSF and AJAX
DOCX
TY.BSc.IT Java QB U5&6
PDF
Java Web Programming [3/9] : Servlet Advanced
PDF
Bea weblogic job_interview_preparation_guide
PDF
Introduction to Spring's Dependency Injection
Struts Introduction Course
Hibernate II
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U4
Hibernate I
Struts notes
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring andspringboot training
Spring Core
JEE5 New Features
TY.BSc.IT Java QB U1
Struts,Jsp,Servlet
Struts course material
Java Web Programming [8/9] : JSF and AJAX
TY.BSc.IT Java QB U5&6
Java Web Programming [3/9] : Servlet Advanced
Bea weblogic job_interview_preparation_guide
Introduction to Spring's Dependency Injection
Ad

Viewers also liked (20)

PDF
Java Day-4
PPTX
MongoDB Session 2
PDF
Identifing Listeners and Filters
PDF
Java Day-2
PDF
Agile Dev. II
PDF
Java Day-7
PPTX
MongoDB Session 1
PDF
Final Table of Content
PDF
Java Day-6
PPTX
Android - Day 2
PDF
Agile Dev. I
PDF
RDBMS with MySQL
PPT
Hibernate presentation
PPT
Basic Hibernate Final
PPT
Introduction to hibernate
PPTX
MongoDB Session 3
PPTX
Ajax and Jquery
PDF
Hibernate An Introduction
Java Day-4
MongoDB Session 2
Identifing Listeners and Filters
Java Day-2
Agile Dev. II
Java Day-7
MongoDB Session 1
Final Table of Content
Java Day-6
Android - Day 2
Agile Dev. I
RDBMS with MySQL
Hibernate presentation
Basic Hibernate Final
Introduction to hibernate
MongoDB Session 3
Ajax and Jquery
Hibernate An Introduction
Ad

Similar to Working with Servlets (20)

PPTX
Servlet session 9
PDF
Lecture 3: Servlets - Session Management
PPT
Session 2 servlet context and session tracking - Giáo trình Bách Khoa Aptech
PPTX
PPTX
J2EE : Java servlet and its types, environment
PPTX
SCWCD : The servlet container : CHAP : 4
PPTX
SERVIET
DOCX
Servlet
PPTX
Session 31 - Session Management, Best Practices, Design Patterns in Web Apps
PDF
08 session-tracking
PDF
08 session-tracking
PPTX
servlets sessions and cookies, jdbc connectivity
PPT
Basics Of Servlet
PDF
JEE Programming - 04 Java Servlets
PPTX
Java - ServletListeners
PDF
Bt0083 server side programing
PPTX
Session 30 - Servlets - Part 6
PPT
Java - Servlet - Mazenet Solution
PPTX
IP UNIT III PPT.pptx
PPTX
ADP - Chapter 2 Exploring the java Servlet Technology
Servlet session 9
Lecture 3: Servlets - Session Management
Session 2 servlet context and session tracking - Giáo trình Bách Khoa Aptech
J2EE : Java servlet and its types, environment
SCWCD : The servlet container : CHAP : 4
SERVIET
Servlet
Session 31 - Session Management, Best Practices, Design Patterns in Web Apps
08 session-tracking
08 session-tracking
servlets sessions and cookies, jdbc connectivity
Basics Of Servlet
JEE Programming - 04 Java Servlets
Java - ServletListeners
Bt0083 server side programing
Session 30 - Servlets - Part 6
Java - Servlet - Mazenet Solution
IP UNIT III PPT.pptx
ADP - Chapter 2 Exploring the java Servlet Technology

More from People Strategists (7)

PPTX
Android - Day 1
PDF
Overview of web services
PPTX
XML Schemas
PPTX
JSON and XML
PPTX
HTML/HTML5
PDF
Java Day-3
Android - Day 1
Overview of web services
XML Schemas
JSON and XML
HTML/HTML5
Java Day-3

Recently uploaded (20)

PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Modernizing your data center with Dell and AMD
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
cuic standard and advanced reporting.pdf
PPTX
Cloud computing and distributed systems.
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Machine learning based COVID-19 study performance prediction
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
A Presentation on Artificial Intelligence
DOCX
The AUB Centre for AI in Media Proposal.docx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Empathic Computing: Creating Shared Understanding
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Modernizing your data center with Dell and AMD
Advanced methodologies resolving dimensionality complications for autism neur...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Dropbox Q2 2025 Financial Results & Investor Presentation
Building Integrated photovoltaic BIPV_UPV.pdf
cuic standard and advanced reporting.pdf
Cloud computing and distributed systems.
Encapsulation_ Review paper, used for researhc scholars
Machine learning based COVID-19 study performance prediction
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
A Presentation on Artificial Intelligence
The AUB Centre for AI in Media Proposal.docx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Empathic Computing: Creating Shared Understanding
Unlocking AI with Model Context Protocol (MCP)
NewMind AI Monthly Chronicles - July 2025
Network Security Unit 5.pdf for BCA BBA.
Build a system with the filesystem maintained by OSTree @ COSCUP 2025

Working with Servlets

  • 1. Slide 1 of 30© People Strategists www.peoplestrategists.com Working with Servlets
  • 2. Slide 2 of 30© People Strategists www.peoplestrategists.com Objectives In this session, you will learn to: Explore the ServletConfig interface Explore the ServletContext interface Implement ServletContext Inerface Introduce session tracking Implement session tracking
  • 3. Slide 3 of 30© People Strategists www.peoplestrategists.com The ServletConfig interface: Is implemented by a Web container during the initialization of a servlet to pass the configuration information to a servlet. Is passed to the init()method of the servlet during initialization. Can be used to pass initialization parameters to the servlets. The initialization parameters are passed as name-value pairs. For example, the connection URL can be passed as an initialization parameter of the servlet. Exploring the ServletConfig Interface
  • 4. Slide 4 of 30© People Strategists www.peoplestrategists.com The following table describes the various methods defined in the ServletConfig interface: Exploring the ServletConfig Interface (Contd.) Method Description String getInitParameter(String param) It returns a String object containing the value of the initialization parameters. Enumeration<String> getInitParameterNames() It returns the names of all the initialization parameters as an enumeration of String objects. ServletContext getServletContext() It returns the ServletContext object for the servlet in which the caller is executing. String getServletName() It returns a String object containing the name of the servlet instance.
  • 5. Slide 5 of 30© People Strategists www.peoplestrategists.com The ServletContext provides the environmental information to the servlets in which they are running. Each Web application consists of only one ServletContext object. A ServletContext object is also known as a Web context. The Web container creates an object of ServletContext at time of deploying the project. Following figure shows the creation of ServletContext object. Exploring the ServletContext Interface ServletContext Object Creation
  • 6. Slide 6 of 30© People Strategists www.peoplestrategists.com The following table describes the various methods defined in the ServletContext interface: Exploring the ServletContext Interface (Contd.) Method Description public void setAttribute(String, Object) Binds the object with a name and stores the name/value pair as an attribute of the ServletContext object. If an attribute already exists, this method replaces the existing attribute. public Object getAttribute(String attrname) Returns the object stored in the ServletContext object with the name passed as a parameter. public Enumeration getAttributeNames() Returns an enumeration of the String object that contains names of all the context attributes. public String getInitParameter(String pname) Returns the value of the initialization parameter with the name passed as a parameter. public Enumeration getInitParameterNames() Returns an enumeration of String object that contains names of all the initialization parameters.
  • 7. Slide 7 of 30© People Strategists www.peoplestrategists.com Usage of the ServletContext interface: The ServletContext object provides an interface between the container and servlet. It can be used to get configuration information from the web.xml file. It can be used to set, get or remove attribute from the web.xml file. It can be used to provide inter-application communication. You can access ServletContext object using the getServletContext method of: The ServletConfig interface, The GenericServlet class The HttpServletRequest interface Exploring the ServletContext Interface (Contd.)
  • 8. Slide 8 of 30© People Strategists www.peoplestrategists.com Accessing ServletContext object using the getServletContext method of the ServletConfig interface: You can use the following code snippet to get the ServletContext object: In the preceding code snippet,  The getServletConfig method returns the object of ServletConfig.  Thereafter, the conf object calls getServletContext that returns the ServletContext object. Implementing the ServletContext Interface ServletConfig conf = getServletConfig(); ServletContext context = conf.getServletContext();
  • 9. Slide 9 of 30© People Strategists www.peoplestrategists.com Consider a scenario where you need to develop a Web application that stores the email and name of user in web.xml file. In addition, you need to access those parameters using ServletContext and display them, as shown in the following figure. Activity: Implementing the ServletContext Interface The Expected Output
  • 10. Slide 10 of 30© People Strategists www.peoplestrategists.com Accessing ServletContext object using the getServletContext method of the GenericServlet class: In general, every servlet class extends HttpServlet, which is a sub class of GenericServlet. Use the following code snippet to access the ServletContext object: In the preceding code snippet, the getServletContext method returns the ServletContext object. Implementing the ServletContext Interface (Contd.) ServletContext context = getServletContext();
  • 11. Slide 11 of 30© People Strategists www.peoplestrategists.com Consider a scenario where you need to develop a Web application that fulfills the following requirements: It should provide a user interface to accept the credentials, as shown in the following figure. It should validate the entered details with value stored in the web.xml file. Activity: Implementing ServletContext Using GenericServlet The Expected Output
  • 12. Slide 12 of 30© People Strategists www.peoplestrategists.com It should display welcome message if the credentials are correct, as shown in the following figure. Activity: Implementing ServletContext Using GenericServlet (Contd.) The Expected Output
  • 13. Slide 13 of 30© People Strategists www.peoplestrategists.com Accessing ServletContext object using the getServletContext method of the HttpRequestServlet interface: You can use the following code snippet to access the ServletContext object: In the preceding code snippet, the req object calls the getServletContext method that returns the ServletContext object. Implementing the ServletContext Interface (Contd.) public void doGet/doPost(HttpServletRequest req, HttpServletResponse res) { ServletContext ctx = req.getServletContext(); }
  • 14. Slide 14 of 30© People Strategists www.peoplestrategists.com Consider a scenario where you need to develop a Web application that fulfills the following requirements: It should provide a user interface to accept the customer details, as shown in the following figure: It should store the entered details to access database. It should display a message “Details are saved.” Activity: Implementing ServletContext Using HttpServletRequest The Expected Output
  • 15. Slide 15 of 30© People Strategists www.peoplestrategists.com Session tracking is the process of maintaining information, or state, about Web site visitors as they move from page to page. The connection from a browser to a Web server occurs over the stateless Hypertext Transfer Protocol (HTTP). Therefore, the Web developer has to explicitly write code to implement session tracking. The mechanism to implement session tracking are: HttpSession Cookie URL Rewriting Introducing Session Tracking
  • 16. Slide 16 of 30© People Strategists www.peoplestrategists.com HttpSession: It is an interface that provides methods to handle session tracking. A session object is created on the application server, usually in a Java servlet or a Java Server Page. The object gets stored on the application server and a unique identifier called a session ID is assigned to it. The object and session ID are handled by a session manager on the application server. Each session ID assigned by the application server has zero or more key/value pairs tied to it. The values are objects that you place in the session. Implementing Session Tracking
  • 17. Slide 17 of 30© People Strategists www.peoplestrategists.com The following table describes the various methods defined in the HttpSession interface: Implementing Session Tracking (Contd.) Method Description public void setAttribute(String name, Object value) Binds the object with a name and stores the name/value pair as an attribute of the HttpSession object. If an attribute already exists, this method replaces the existing attribute. public Object getAttribute(String name) Retrieves the String object specified in the parameter, from the session object. If no object is found for the specified attribute, the getAttribute()method returns null. public Enumeration getAttributeNames() Returns an Enumeration object that contains the name of all the objects that are bound as attributes to the session object. public void removeAttribute(String name) Removes the object bound with the specified name from this session. public void invalidate() Invalidates this session and unbinds any objects bound to it. public Boolean isNew() Returns a Boolean with a value of true if the client does not yet know about the session or if the client chooses not to join the session
  • 18. Slide 18 of 30© People Strategists www.peoplestrategists.com To use HttpSession object, you need to: Create and retrieve session object using the getSession method of HttpServletRequest. Following code snippet shows an example: The getSession method is passed a boolean value. The false value indicates that you want to retrieve an existing session object. The true value lets the session manager know that a session object needs to be created if one does not already exist. Implementing Session Tracking (Contd.) HttpSession session = request.getSession(true);
  • 19. Slide 19 of 30© People Strategists www.peoplestrategists.com An object of HttpSession can find out that the session is new or can remove one. Following code snippet shows an example: In the above code snippet, the existing session object gets removed and a new session object is created. Implementing Session Tracking (Contd.) HttpSession session = request.getSession (true); if (session.isNew() == false) { session.invalidate(); session = request.getSession(true); }
  • 20. Slide 20 of 30© People Strategists www.peoplestrategists.com You need to develop a Web application that allows users to buy products online. The application should be based on the following guidelines: It should provide a login page, as sown in the following figure. Activity: Implementing Session Tracking Using HttpSession The Expected Output
  • 21. Slide 21 of 30© People Strategists www.peoplestrategists.com It should display a Web page to select brands of shirts, as sown in the following figure. Activity: Implementing Session Tracking Using HttpSession (Contd.) The Expected Output
  • 22. Slide 22 of 30© People Strategists www.peoplestrategists.com It should display the bill based on the selection, as shown in the following figure. Activity: Implementing Session Tracking Using HttpSession (Contd.) The Expected Output
  • 23. Slide 23 of 30© People Strategists www.peoplestrategists.com Cookie: Is information that is stored as a name/value pair. Is transmitted from the server to the browser. Is a common way of session tracking. Cookies can be used to tie specific visitors to information about them on the server. The Java servlet specification provides a simple cookie API that allows you to write and retrieve cookies. Following code snippet creates a Cookie object: The Cookie object is valid for one hour. The response object adds the cookie for later use. Implementing Session Tracking (Contd.) Cookie user = new Cookie("user","Jennifer"); user.setMaxAge(3600); response.addCookie(user);
  • 24. Slide 24 of 30© People Strategists www.peoplestrategists.com Following code snippet retrieves the Cookie object: The getCookies method retrieves the stored cookies. The getName method returns the cookie name. The getValue method returns the value stored in cookie. Implementing Session Tracking (Contd.) String user = ""; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("user")) user =cookies[i].getValue(); } }
  • 25. Slide 25 of 30© People Strategists www.peoplestrategists.com You need to develop a Web application that accepts the name of a user and writes it to cookie. For this, you need to create a user interface, as shown in the following figure. Activity: Implementing Session Tracking Using Cookie The Expected Output
  • 26. Slide 26 of 30© People Strategists www.peoplestrategists.com In addition, you need to read the cookie value and display it, as shown in the following figure. Activity: Implementing Session Tracking Using Cookie (Contd.) The Expected Output
  • 27. Slide 27 of 30© People Strategists www.peoplestrategists.com URL Rewriting: is the lowest common denominator of session tracking. Can be used for session tracking if client does not support cookies. Involves adding data, a session ID, to the URL path that is interpreted by the container to associate the request with a session. In URL rewriting, users append a token or identifier to the URL of the next Servlet or the next resource. Implementing Session Tracking (Contd.)
  • 28. Slide 28 of 30© People Strategists www.peoplestrategists.com The HttpServletResponse interface provides following two methods for URL Rewriting: encodeURL(String):  Encodes the specified URL by including the session ID in it.  Returns the URL unchanged if encoding is not needed. URLencodeRedirectURL(String):  Encodes the specified URL for use in the sendRedirect method.  Returns the URL unchanged if encoding is not needed.  All URLs sent to the HttpServletResponse.sendRedirect method should be run through this method. Otherwise, URL rewriting cannot be used with browsers which do not support cookies. Implementing Session Tracking (Contd.)
  • 29. Slide 29 of 30© People Strategists www.peoplestrategists.com Summary In this session, you learned that: ServletConfig is implemented by a Web container during the initialization of a servlet to pass the configuration information to a servlet. ServletContext provides the environmental information to the servlets in which they are running. Usage of the ServletContext interface are:  It can be used to get configuration information from the web.xml file.  It can be used to set, get or remove attribute from the web.xml file.  It can be used to provide inter-application communication. Session tracking is the process of maintaining information, or state, about Web site visitors as they move from page to page. The mechanism to implement session tracking are:  HttpSession  Cookie  URL Rewriting
  • 30. Slide 30 of 30© People Strategists www.peoplestrategists.com Summary (Contd.) HttpSession is an interface that provides methods to handle session tracking. Cookie is information that is stored as a name/value pair and is transmitted from the server to the browser. It Is a common way of session tracking. URL Rewriting can be used for session tracking if client does not support cookies. It Involves adding data, a session ID, to the URL path that is interpreted by the container to associate the request with a session.