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

What's hot (19)

PPT
Struts Introduction Course
guest764934
 
PDF
Hibernate II
People Strategists
 
DOCX
TY.BSc.IT Java QB U3
Lokesh Singrol
 
DOCX
TY.BSc.IT Java QB U4
Lokesh Singrol
 
PDF
Hibernate I
People Strategists
 
DOCX
Struts notes
Rajeev Uppala
 
PDF
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Raghavan Mohan
 
PPTX
Spring andspringboot training
Mallikarjuna G D
 
PPT
Spring Core
Pushan Bhattacharya
 
PPT
JEE5 New Features
Haitham Raik
 
DOCX
TY.BSc.IT Java QB U1
Lokesh Singrol
 
PPT
Struts,Jsp,Servlet
dasguptahirak
 
PPT
Struts course material
Vibrant Technologies & Computers
 
PDF
Java Web Programming [8/9] : JSF and AJAX
IMC Institute
 
DOCX
TY.BSc.IT Java QB U5&6
Lokesh Singrol
 
PDF
Java Web Programming [3/9] : Servlet Advanced
IMC Institute
 
PDF
Bea weblogic job_interview_preparation_guide
Pankaj Singh
 
PDF
Introduction to Spring's Dependency Injection
Richard Paul
 
Struts Introduction Course
guest764934
 
Hibernate II
People Strategists
 
TY.BSc.IT Java QB U3
Lokesh Singrol
 
TY.BSc.IT Java QB U4
Lokesh Singrol
 
Hibernate I
People Strategists
 
Struts notes
Rajeev Uppala
 
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Raghavan Mohan
 
Spring andspringboot training
Mallikarjuna G D
 
Spring Core
Pushan Bhattacharya
 
JEE5 New Features
Haitham Raik
 
TY.BSc.IT Java QB U1
Lokesh Singrol
 
Struts,Jsp,Servlet
dasguptahirak
 
Struts course material
Vibrant Technologies & Computers
 
Java Web Programming [8/9] : JSF and AJAX
IMC Institute
 
TY.BSc.IT Java QB U5&6
Lokesh Singrol
 
Java Web Programming [3/9] : Servlet Advanced
IMC Institute
 
Bea weblogic job_interview_preparation_guide
Pankaj Singh
 
Introduction to Spring's Dependency Injection
Richard Paul
 

Viewers also liked (20)

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

Similar to Working with Servlets (20)

PPTX
Servlet session 9
Anuj Singh Rajput
 
PPT
Session 2 servlet context and session tracking - Giáo trình Bách Khoa Aptech
MasterCode.vn
 
PPTX
SCWCD : The servlet container : CHAP : 4
Ben Abdallah Helmi
 
PPT
Java servlet life cycle - methods ppt
kamal kotecha
 
PDF
Murach : How to work with session state and cookies
MahmoudOHassouna
 
PDF
Mvc acchitecture
laxmi.katkar
 
PPT
Servlet ppt by vikas jagtap
Vikas Jagtap
 
PPTX
Servlets
Geethu Mohan
 
PPTX
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
SharePoint Saturday NY
 
PPTX
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
dioduong345
 
PPT
Servlet11
patinijava
 
PDF
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
WebStackAcademy
 
PPTX
Asp objects
RajaRajeswari22
 
PDF
OpenDMS - the first 2 weeks
JPC Hanson
 
ODP
servlet 2.5 & JSP 2.0
megrhi haikel
 
PPTX
J2EE : Java servlet and its types, environment
joearunraja2
 
PPT
Servlet 01
Bharat777
 
PDF
Mvc interview questions – deep dive jinal desai
jinaldesailive
 
PDF
INTRODUCTION TO CLIENT SIDE PROGRAMMING
Prof Ansari
 
Servlet session 9
Anuj Singh Rajput
 
Session 2 servlet context and session tracking - Giáo trình Bách Khoa Aptech
MasterCode.vn
 
SCWCD : The servlet container : CHAP : 4
Ben Abdallah Helmi
 
Java servlet life cycle - methods ppt
kamal kotecha
 
Murach : How to work with session state and cookies
MahmoudOHassouna
 
Mvc acchitecture
laxmi.katkar
 
Servlet ppt by vikas jagtap
Vikas Jagtap
 
Servlets
Geethu Mohan
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
SharePoint Saturday NY
 
8-9-10. ASP_updated8-9-10. ASP_updated8-9-10. ASP_updated
dioduong345
 
Servlet11
patinijava
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
WebStackAcademy
 
Asp objects
RajaRajeswari22
 
OpenDMS - the first 2 weeks
JPC Hanson
 
servlet 2.5 & JSP 2.0
megrhi haikel
 
J2EE : Java servlet and its types, environment
joearunraja2
 
Servlet 01
Bharat777
 
Mvc interview questions – deep dive jinal desai
jinaldesailive
 
INTRODUCTION TO CLIENT SIDE PROGRAMMING
Prof Ansari
 
Ad

More from People Strategists (7)

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

Recently uploaded (20)

PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
July Patch Tuesday
Ivanti
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
PDF
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
PDF
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
July Patch Tuesday
Ivanti
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
IoT-Powered Industrial Transformation – Smart Manufacturing to Connected Heal...
Rejig Digital
 
From Code to Challenge: Crafting Skill-Based Games That Engage and Reward
aiyshauae
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
CIFDAQ Weekly Market Wrap for 11th July 2025
CIFDAQ
 
HubSpot Main Hub: A Unified Growth Platform
Jaswinder Singh
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 

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.