SlideShare a Scribd company logo
1 of 30
Download to read offline
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

Struts Introduction Course
Struts Introduction CourseStruts Introduction Course
Struts Introduction Courseguest764934
 
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorialsSpring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorialsRaghavan Mohan
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot trainingMallikarjuna G D
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXIMC Institute
 
TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6Lokesh Singrol
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedIMC Institute
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guidePankaj Singh
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionRichard Paul
 

What's hot (19)

Struts Introduction Course
Struts Introduction CourseStruts Introduction Course
Struts Introduction Course
 
Hibernate II
Hibernate IIHibernate II
Hibernate II
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4TY.BSc.IT Java QB U4
TY.BSc.IT Java QB U4
 
Hibernate I
Hibernate IHibernate I
Hibernate I
 
Jdbc
JdbcJdbc
Jdbc
 
Struts notes
Struts notesStruts notes
Struts notes
 
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorialsSpring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
 
Spring andspringboot training
Spring andspringboot trainingSpring andspringboot training
Spring andspringboot training
 
Spring Core
Spring CoreSpring Core
Spring Core
 
JEE5 New Features
JEE5 New FeaturesJEE5 New Features
JEE5 New Features
 
TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1
 
Struts,Jsp,Servlet
Struts,Jsp,ServletStruts,Jsp,Servlet
Struts,Jsp,Servlet
 
Struts course material
Struts course materialStruts course material
Struts course material
 
Java Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAXJava Web Programming [8/9] : JSF and AJAX
Java Web Programming [8/9] : JSF and AJAX
 
TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6TY.BSc.IT Java QB U5&6
TY.BSc.IT Java QB U5&6
 
Java Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet AdvancedJava Web Programming [3/9] : Servlet Advanced
Java Web Programming [3/9] : Servlet Advanced
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 

Viewers also liked (20)

Java Day-4
Java Day-4Java Day-4
Java Day-4
 
MongoDB Session 2
MongoDB Session 2MongoDB Session 2
MongoDB Session 2
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
 
Java Day-2
Java Day-2Java Day-2
Java Day-2
 
Agile Dev. II
Agile Dev. IIAgile Dev. II
Agile Dev. II
 
Java Day-7
Java Day-7Java Day-7
Java Day-7
 
MongoDB Session 1
MongoDB Session 1MongoDB Session 1
MongoDB Session 1
 
Final Table of Content
Final Table of ContentFinal Table of Content
Final Table of Content
 
Java Day-6
Java Day-6Java Day-6
Java Day-6
 
Android - Day 2
Android - Day 2Android - Day 2
Android - Day 2
 
Agile Dev. I
Agile Dev. IAgile Dev. I
Agile Dev. I
 
RDBMS with MySQL
RDBMS with MySQLRDBMS with MySQL
RDBMS with MySQL
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Basic Hibernate Final
Basic Hibernate FinalBasic Hibernate Final
Basic Hibernate Final
 
JDBC
JDBCJDBC
JDBC
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
MongoDB Session 3
MongoDB Session 3MongoDB Session 3
MongoDB Session 3
 
Ajax and Jquery
Ajax and JqueryAjax and Jquery
Ajax and Jquery
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate An Introduction
Hibernate An IntroductionHibernate An Introduction
Hibernate An Introduction
 

Similar to Working with Servlets

Session 2 servlet context and session tracking - Giáo trình Bách Khoa Aptech
Session 2   servlet context and session tracking - Giáo trình Bách Khoa AptechSession 2   servlet context and session tracking - Giáo trình Bách Khoa Aptech
Session 2 servlet context and session tracking - Giáo trình Bách Khoa AptechMasterCode.vn
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4Ben Abdallah Helmi
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookiesMahmoudOHassouna
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...SharePoint Saturday NY
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...WebStackAcademy
 
OpenDMS - the first 2 weeks
OpenDMS - the first 2 weeksOpenDMS - the first 2 weeks
OpenDMS - the first 2 weeksJPC Hanson
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0megrhi haikel
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentjoearunraja2
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desaijinaldesailive
 
INTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMINGINTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMINGProf Ansari
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVCSunpawet Somsin
 

Similar to Working with Servlets (20)

Servlet session 9
Servlet   session 9Servlet   session 9
Servlet session 9
 
Session 2 servlet context and session tracking - Giáo trình Bách Khoa Aptech
Session 2   servlet context and session tracking - Giáo trình Bách Khoa AptechSession 2   servlet context and session tracking - Giáo trình Bách Khoa Aptech
Session 2 servlet context and session tracking - Giáo trình Bách Khoa Aptech
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Murach : How to work with session state and cookies
Murach : How to work with session state and cookiesMurach : How to work with session state and cookies
Murach : How to work with session state and cookies
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Servlets
ServletsServlets
Servlets
 
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
Lyudmila Zharova: Developing Solutions for SharePoint 2010 Using the Client O...
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
Servlet11
Servlet11Servlet11
Servlet11
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Asp objects
Asp objectsAsp objects
Asp objects
 
OpenDMS - the first 2 weeks
OpenDMS - the first 2 weeksOpenDMS - the first 2 weeks
OpenDMS - the first 2 weeks
 
servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0servlet 2.5 & JSP 2.0
servlet 2.5 & JSP 2.0
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
Servlet 01
Servlet 01Servlet 01
Servlet 01
 
Mvc interview questions – deep dive jinal desai
Mvc interview questions – deep dive   jinal desaiMvc interview questions – deep dive   jinal desai
Mvc interview questions – deep dive jinal desai
 
INTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMINGINTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMING
 
Introduction to ASP.NET MVC
Introduction to ASP.NET MVCIntroduction to ASP.NET MVC
Introduction to ASP.NET MVC
 

More from People Strategists (7)

Android - Day 1
Android - Day 1Android - Day 1
Android - Day 1
 
Overview of web services
Overview of web servicesOverview of web services
Overview of web services
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
 
JSON and XML
JSON and XMLJSON and XML
JSON and XML
 
CSS
CSSCSS
CSS
 
HTML/HTML5
HTML/HTML5HTML/HTML5
HTML/HTML5
 
Java Day-3
Java Day-3Java Day-3
Java Day-3
 

Recently uploaded

Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 

Recently uploaded (20)

Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 

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.