SlideShare a Scribd company logo
Java & JEE Training
Session 31 – Session Management using Servlets
+Design Patterns
Page 1Classification: Restricted
Agenda
• Session Management and Tracking
• Best Practices
• Design Patterns
• Cookies
Page 2Classification: Restricted
Review of previous session…
….
Page 3Classification: Restricted
Web Server and Application Server
Presentation Tier:
JSP, Servlets
Run on Web Server
or container
JDBC on web server
or app server
Database
Client:
HTML JS CSS
(Run on client
machine on the
browser)
Java & JEE Training
Understanding scope: parameters, attributes
Page 5Classification: Restricted
Web.xml file: Servlet mapping to URL
Page 6Classification: Restricted
Requests, Sessions, Application
• Request: The client sending an HTTP request to the server.
• Session: Is a set of requests coming in from the client from the point that
the client logs in to the point that the client logs out.
• Application: The time that the application (or server) is up and running.
• An application may have multiple sessions.
• A session may have multiple requests.
Page 7Classification: Restricted
HTTP IS STATELESS
CLIENT SERVER
LOGIN ID AND
PASSWORD
LOGIN SUCCESSFUL
ENQUIRE ACCOUNT
DETAILS
I DON’T KNOW YOU.
PLEASE LOGIN…
SESSION
- COOKIES…
HOW DO I MAINTAIN
SESSIONS?
Page 8Classification: Restricted
HTTP IS STATELESS
CLIENT SERVER
LOGIN ID AND
PASSWORD
LOGIN SUCCESSFUL;
SESSIONID=1234;
ENQUIRE ACCOUNT
DETAILS;SESSIONID=1234;
I DON’T KNOW YOU.
PLEASE LOGIN…
SESSION
- COOKIES
HOW DO I MAINTAIN
SESSIONS?
Page 9Classification: Restricted
Parameters vs Attributes
• Parameters may come into our application from the client request, or may be
configured through deployment descriptor (web.xml) elements or their
corresponding annotations. When you submit a form, form values are sent as
request parameters to a web application. In case of a GET request, these
parameters are exposed in the URL as name value pairs and in case of
POST, parameters are sent within the body of the request.
• Servlet init parameters and context init parameters are set through the deployment
descriptor (web.xml) or their corresponding annotations. All parameters are read-
only from the application code. We have methods in the Servlet API to retrieve
various parameters.
• Attributes are objects that are attached to various scopes and can be
modified, retrieved or removed. Attributes can be read, created, updated and
deleted by the web container as well as our application code. We have methods in
the Servlet API to add, modify, retrieve and remove attributes. When an object is
added to an attribute in any scope, it is called binding as the object is bound into a
scoped attribute with a given name.
Page 10Classification: Restricted
Parameters vs Attributes
• Parameters are read only Strings, attributes are read/write objects.
• Parameters are String objects, attributes can be objects of any type.
Page 11Classification: Restricted
Methods to manipulate parameters
• Request: (Request time constant)
ServletRequest.getParameter(paramname);
ServletRequest.getParameterNames();
• ServletConfig init parameters: (Deployment time constant)
ServletConfig.getInitParameterNames()
ServletConfig.getInitParameter(String paramName)
• ServletContext init parameters: (Deployment time constant)
ServletContext.getInitParameterNames()
ServletContext.getInitParameter(String paramName)
AVAILABLE FOR
THE REQUEST
AVAILABLE FOR
THE SERVLET
AVAILABLE FOR
THE WHOLE
APPLICATION
Page 12Classification: Restricted
Web.xml : init parameters (Servlet Scope)
Page 13Classification: Restricted
Web.xml: Init parameters (Application scope)
Page 14Classification: Restricted
ServletConfig vs ServletContext
• ServletConfig // Available for a specific servlet
• ServletConfig available in javax.servlet.*; package
• ServletConfig object is one per servlet class
• Object of ServletConfig will be created during initialization process of the servlet
• This Config object is public to a particular servlet only
• Scope: As long as a servlet is executing, ServletConfig object will be available, it will be
destroyed once the servlet execution is completed.
• We should give request explicitly, in order to create ServletConfig object for the first time
• In web.xml – <init-param> tag will be appear under <servlet-class> tag
• ServletContext // Available for whole application
• ServletContext available in javax.servlet.*; package
• ServletContext object is global to entire web application
• Object of ServletContext will be created at the time of web application deployment
• Scope: As long as web application is executing, ServletContext object will be available, and
it will be destroyed once the application is removed from the server.
• ServletContext object will be available even before giving the first request
• In web.xml – <context-param> tag will be appear under <web-app> tag
Page 15Classification: Restricted
How to get servletContext?
getServletConfig( ).getServletContext( );
request.getSession( ).getServletContext( );
getServletContext( );
request.getServletContext();
Page 16Classification: Restricted
Understanding scope of attributes
• Similar to scope and lifetime of variables in Java as you have seen in blocks
and methods in java, parameters and attributes in a Java EE web
application also have scope and lifetime in the context of the web
application.
• The scope of a parameter/attribute denotes the availability of that
parameter/attribute for use. A web application serves multiple requests
from clients when it is up and running. These requests can be from same
client or different clients. We have seen from the servlet life cycle that a
servlet’s service() method is called every time a request comes.
Page 17Classification: Restricted
Scoping in Servlets and JSP
• Request scope
• Session scope
• Application or context scope
• Page scope (only for JSP)
Page 18Classification: Restricted
Request Scope
• Request scope start from the moment an HTTP request hits a servlet in our web
container and end when the servlet is done with delivering the HTTP response.
• With respect to the servlet life cycle, the request scope begins on entry to a
servlet’s service() method and ends on the exit from that method.
• A ‘request’ scope parameter/attribute can be accessed from any of servlets or jsps
that are part of serving one request. For example, you call one servlet/jsp, it then
calls another servlet/jsp and so on, and finally the response is sent back to the
client.
• Request scope is denoted by javax.servlet.http.HttpServletRequest interface.
• Container passes the request object as an argument of type HttpServletRequest to
Servlet's service method.
• Request object is available in a JSP page as an implicit object called request. You
can set value for an attribute in request object from a servlet and get it from a JSP
within the same request using the implicit request object.
Page 19Classification: Restricted
Session scope
• A session scope starts when a client (e.g. browser window) establishes
connection with our web application till the point where the browser
window is closed.
• Session scope spans across multiple requests from the same client.
• A notable feature of tabbed browsing is that session is shared between the
tabs and hence you can requests from other tabs too during a session
without logging in again. For instance, you can load your Gmail inbox in
another tab without logging in again. This also means browsing an unknown
site and a secure site from different tabs from the same browser can
expose your secure session ID to malicious applications. So always open a
new browser window when you want to do secure transactions, especially
financial transactions.
• Session scope is denoted by javax.servlet.http.HttpSession interface.
• Session object is available in a JSP page as an implicit object called session.
• In a servlet, you can get Session object by calling request.getSession().
Page 20Classification: Restricted
Application or context scope
• Context scope or application scope starts from the point where a web
application is put into service (started) till it is removed from service
(shutdown) or the web application is reloaded.
Parameters/attributes within the application scope will be available to all
requests and sessions.
• Application scope is denoted by javax.servlet.ServletContext interface.
• Application object is available in a JSP page as an implicit
object called application.
• In a servlet, you can get application object by
calling getServletContext() from within the servlets code directly (the
servlet itself implements the ServletConfig interface that contains this
method) or by explicitly calling getServletConfig().getServletContext().
• The web container provides one ServletContext object per web application
per JVM.
Page 21Classification: Restricted
Page scope (Only for JSP, not for Servlets)
• The page scope restricts the scpoe and lifetime of attributes to the same
page where it was created.
• Page scope is denoted by javax.servlet.jsp.PageContext abstract class.
• It is available in a JSP page as an implicit object called pageScope
Page 22Classification: Restricted
Servlets – Scope at a glance
• Application scope
request.getServletContext();
request.getServletContext().setAttribute("attribute_name","value")
• Session scope
request.getSession(); //going to create the session if session is not exist.
request.getSession(false); // Not going to create the session.
session.getAttribute("attribute_name");
• Request scope
request.setAttribute("attribute_name","value");
request.getAttribute("attribute_name"); // return the Object you have to
cast it
Java & JEE Training
Session tracking with servlets
Page 24Classification: Restricted
HTTP IS STATELESS
CLIENT SERVER
LOGIN ID AND
PASSWORD
LOGIN SUCCESSFUL
ENQUIRE ACCOUNT
DETAILS
I DON’T KNOW YOU.
PLEASE LOGIN…
SESSION
- COOKIES…
HOW DO I MAINTAIN
SESSIONS?
Page 25Classification: Restricted
HTTP IS A STATELESS PROTOCOL
CLIENT SERVER
LOGIN ID AND
PASSWORD
LOGIN SUCCESSFUL;
SESSIONID=1234;
ENQUIRE ACCOUNT
DETAILS;SESSIONID=1234;
I DON’T KNOW YOU.
PLEASE LOGIN…
SESSION
- COOKIES
HOW DO I MAINTAIN
SESSIONS?
Page 26Classification: Restricted
Why track sessions?
• HTTP is stateless protocol
• So we need to maintain state across multiple requests of a session using
session tracking techniques.
• Session tracking techniques:
• Cookies
• Hidden Form Field
• URL Rewriting
• HttpSession
Page 27Classification: Restricted
How cookies work?
Page 28Classification: Restricted
Using cookies
• javax.servlet.http.Cookie class
• Creating a cookie:
Cookie ck=new Cookie("user",“pawan");//creating cookie object
response.addCookie(ck);//adding cookie in the response
• Deleting a cookie
Cookie ck=new Cookie("user","");//deleting value of cookie
ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response
• Get all cookies from request:
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing cookies info
}
Page 29Classification: Restricted
Example
• Demo of using cookies
Page 30Classification: Restricted
Hidden form fields…
• A web server can send a hidden HTML form field along with a unique session ID as
follows:
<input type="hidden" name="sessionid" value="12345">
• This entry means that, when the form is submitted, the specified name and value
are automatically included in the GET or POST data. Each time when web browser
sends request back, then session_id value can be used to keep the track of different
web browsers.
• Advantage of Hidden Form Field
• It will always work whether cookie is disabled or not.
• Disadvantage of Hidden Form Field:
• It is maintained at server side.
• Extra form submission is required on each pages.
• Only textual information can be used.
Page 31Classification: Restricted
URL Rewriting
• You can append some extra data on the end of each URL that identifies the session,
and the server can associate that session identifier with data it has stored about
that session.
• For example, with http://mycompany.com/file.htm;sessionid=12345, the session
identifier is attached as sessionid=12345 which can be accessed at the web server
to identify the client.
• URL rewriting is a better way to maintain sessions and works for the browsers when
they don't support cookies but here drawback is that you would have generate
every URL dynamically to assign a session ID though page is simple static HTML
page.
• Advantage of URL Rewriting
• It will always work whether cookie is disabled or not (browser independent).
• Extra form submission is not required on each pages.
• Disadvantage of URL Rewriting
• It will work only with links.
• It can send Only textual information.
Page 32Classification: Restricted
Using HttpSession
• HttpSession object is used to store entire session with a specific client. We
can store, retrieve and remove attribute from HttpSession object. Any
servlet can have access to HttpSession object throughout the getSession()
method of the HttpServletRequest object.
Page 33Classification: Restricted
Important HttpSession Methods
Methods Description
long getCreationTime() returns the time when the session was
created, measured in milliseconds since
midnight January 1, 1970 GMT.
String getId() returns a string containing the unique
identifier assigned to the session.
long getLastAccessedTime() returns the last time the client sent a
request associated with the session
int getMaxInactiveInterval() returns the maximum time interval, in
seconds.
void invalidate() destroy the session
boolean isNew() returns true if the session is new else false
void setMaxInactiveInterval(int interval) Specifies the time, in seconds,after servlet
container will invalidate the session.
Page 34Classification: Restricted
HttpSession usage
Page 35Classification: Restricted
HttpSession Demo
• Demo
• Write a login / logout application using HttpSession
Page 36Classification: Restricted
Topics to be covered in next session
• Session tracking with servlets
Page 37Classification: Restricted
Thank you!

More Related Content

PPTX
Flutter workshop
PPTX
Introduction to DevOps
PDF
Version Control & Git
PDF
GIT | Distributed Version Control System
PDF
Introduction to Spring Cloud
PDF
Building a DevSecOps Pipeline Around Your Spring Boot Application
PPTX
Flutter Intro
PDF
State of Micro Frontend
Flutter workshop
Introduction to DevOps
Version Control & Git
GIT | Distributed Version Control System
Introduction to Spring Cloud
Building a DevSecOps Pipeline Around Your Spring Boot Application
Flutter Intro
State of Micro Frontend

What's hot (20)

PPTX
Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...
PPTX
Démystifier la programmation avec LabVIEW FPGA
PDF
Observability for modern applications
PDF
gRPC with java
PDF
Google flutter the easy and practical way
PPTX
Introduction to microservices
PPTX
Flutter introduction
PDF
Getting started with AppArmor
PDF
Test strategies for data processing pipelines
PDF
Apache Sling : JCR, OSGi, Scripting and REST
PPTX
Building Data Pipelines for Solr with Apache NiFi
PPTX
Full stack web development
PDF
Networking in Java with NIO and Netty
PDF
REST APIs with Spring
PDF
Understanding Reactive Programming
PDF
Spring Boot
PDF
Gain Deep Visibility into APIs and Integrations with Anypoint Monitoring
PDF
Android Security Internals
PPTX
Implementing DDD with C#
ODP
Introduction to Version Control
Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...
Démystifier la programmation avec LabVIEW FPGA
Observability for modern applications
gRPC with java
Google flutter the easy and practical way
Introduction to microservices
Flutter introduction
Getting started with AppArmor
Test strategies for data processing pipelines
Apache Sling : JCR, OSGi, Scripting and REST
Building Data Pipelines for Solr with Apache NiFi
Full stack web development
Networking in Java with NIO and Netty
REST APIs with Spring
Understanding Reactive Programming
Spring Boot
Gain Deep Visibility into APIs and Integrations with Anypoint Monitoring
Android Security Internals
Implementing DDD with C#
Introduction to Version Control
Ad

Similar to Session 31 - Session Management, Best Practices, Design Patterns in Web Apps (20)

PPTX
Session 30 - Servlets - Part 6
PPTX
Session 29 - Servlets - Part 5
PPTX
Session 26 - Servlets Part 2
PDF
Lecture 3: Servlets - Session Management
PPTX
SCWCD : The servlet container : CHAP : 4
PPTX
J2EE : Java servlet and its types, environment
PPTX
Servlet session 9
PPTX
Session 25 - Introduction to JEE, Servlets
PPT
Session 2 servlet context and session tracking - Giáo trình Bách Khoa Aptech
ODP
servlet 2.5 & JSP 2.0
PDF
Bt0083 server side programing
DOCX
Servlet
PDF
Working with Servlets
PPTX
SCWCD : Thread safe servlets : CHAP : 8
PPT
Java - Servlet - Mazenet Solution
PPTX
Core web application development
PPT
Basics Of Servlet
PPTX
Session 33 - Session Management using other Techniques
PPTX
Integrating Servlets and JSP (The MVC Architecture)
PPTX
servlets sessions and cookies, jdbc connectivity
Session 30 - Servlets - Part 6
Session 29 - Servlets - Part 5
Session 26 - Servlets Part 2
Lecture 3: Servlets - Session Management
SCWCD : The servlet container : CHAP : 4
J2EE : Java servlet and its types, environment
Servlet session 9
Session 25 - Introduction to JEE, Servlets
Session 2 servlet context and session tracking - Giáo trình Bách Khoa Aptech
servlet 2.5 & JSP 2.0
Bt0083 server side programing
Servlet
Working with Servlets
SCWCD : Thread safe servlets : CHAP : 8
Java - Servlet - Mazenet Solution
Core web application development
Basics Of Servlet
Session 33 - Session Management using other Techniques
Integrating Servlets and JSP (The MVC Architecture)
servlets sessions and cookies, jdbc connectivity
Ad

More from PawanMM (20)

PPTX
Session 48 - JS, JSON and AJAX
PPTX
Session 46 - Spring - Part 4 - Spring MVC
PPTX
Session 45 - Spring - Part 3 - AOP
PPTX
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
PPTX
Session 43 - Spring - Part 1 - IoC DI Beans
PPTX
Session 42 - Struts 2 Hibernate Integration
PPTX
Session 41 - Struts 2 Introduction
PPTX
Session 40 - Hibernate - Part 2
PPTX
Session 39 - Hibernate - Part 1
PPTX
Session 38 - Core Java (New Features) - Part 1
PPTX
Session 37 - JSP - Part 2 (final)
PPTX
Session 36 - JSP - Part 1
PPTX
Session 35 - Design Patterns
PPTX
Session 34 - JDBC Best Practices, Introduction to Design Patterns
PPTX
Session 32 - Session Management using Cookies
PPTX
Session 28 - Servlets - Part 4
PPTX
Session 24 - JDBC, Intro to Enterprise Java
PPTX
Session 23 - JDBC
PPTX
Session 22 - Java IO, Serialization
PPTX
Session 21 - Inner Classes
Session 48 - JS, JSON and AJAX
Session 46 - Spring - Part 4 - Spring MVC
Session 45 - Spring - Part 3 - AOP
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
Session 43 - Spring - Part 1 - IoC DI Beans
Session 42 - Struts 2 Hibernate Integration
Session 41 - Struts 2 Introduction
Session 40 - Hibernate - Part 2
Session 39 - Hibernate - Part 1
Session 38 - Core Java (New Features) - Part 1
Session 37 - JSP - Part 2 (final)
Session 36 - JSP - Part 1
Session 35 - Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design Patterns
Session 32 - Session Management using Cookies
Session 28 - Servlets - Part 4
Session 24 - JDBC, Intro to Enterprise Java
Session 23 - JDBC
Session 22 - Java IO, Serialization
Session 21 - Inner Classes

Recently uploaded (20)

PPTX
MYSQL Presentation for SQL database connectivity
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Machine learning based COVID-19 study performance prediction
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Electronic commerce courselecture one. Pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
Cloud computing and distributed systems.
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Encapsulation theory and applications.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
MYSQL Presentation for SQL database connectivity
Building Integrated photovoltaic BIPV_UPV.pdf
Machine learning based COVID-19 study performance prediction
Review of recent advances in non-invasive hemoglobin estimation
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
CIFDAQ's Market Insight: SEC Turns Pro Crypto
“AI and Expert System Decision Support & Business Intelligence Systems”
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Unlocking AI with Model Context Protocol (MCP)
Electronic commerce courselecture one. Pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
NewMind AI Monthly Chronicles - July 2025
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Cloud computing and distributed systems.
NewMind AI Weekly Chronicles - August'25 Week I
Digital-Transformation-Roadmap-for-Companies.pptx
Encapsulation theory and applications.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?

Session 31 - Session Management, Best Practices, Design Patterns in Web Apps

  • 1. Java & JEE Training Session 31 – Session Management using Servlets +Design Patterns
  • 2. Page 1Classification: Restricted Agenda • Session Management and Tracking • Best Practices • Design Patterns • Cookies
  • 3. Page 2Classification: Restricted Review of previous session… ….
  • 4. Page 3Classification: Restricted Web Server and Application Server Presentation Tier: JSP, Servlets Run on Web Server or container JDBC on web server or app server Database Client: HTML JS CSS (Run on client machine on the browser)
  • 5. Java & JEE Training Understanding scope: parameters, attributes
  • 6. Page 5Classification: Restricted Web.xml file: Servlet mapping to URL
  • 7. Page 6Classification: Restricted Requests, Sessions, Application • Request: The client sending an HTTP request to the server. • Session: Is a set of requests coming in from the client from the point that the client logs in to the point that the client logs out. • Application: The time that the application (or server) is up and running. • An application may have multiple sessions. • A session may have multiple requests.
  • 8. Page 7Classification: Restricted HTTP IS STATELESS CLIENT SERVER LOGIN ID AND PASSWORD LOGIN SUCCESSFUL ENQUIRE ACCOUNT DETAILS I DON’T KNOW YOU. PLEASE LOGIN… SESSION - COOKIES… HOW DO I MAINTAIN SESSIONS?
  • 9. Page 8Classification: Restricted HTTP IS STATELESS CLIENT SERVER LOGIN ID AND PASSWORD LOGIN SUCCESSFUL; SESSIONID=1234; ENQUIRE ACCOUNT DETAILS;SESSIONID=1234; I DON’T KNOW YOU. PLEASE LOGIN… SESSION - COOKIES HOW DO I MAINTAIN SESSIONS?
  • 10. Page 9Classification: Restricted Parameters vs Attributes • Parameters may come into our application from the client request, or may be configured through deployment descriptor (web.xml) elements or their corresponding annotations. When you submit a form, form values are sent as request parameters to a web application. In case of a GET request, these parameters are exposed in the URL as name value pairs and in case of POST, parameters are sent within the body of the request. • Servlet init parameters and context init parameters are set through the deployment descriptor (web.xml) or their corresponding annotations. All parameters are read- only from the application code. We have methods in the Servlet API to retrieve various parameters. • Attributes are objects that are attached to various scopes and can be modified, retrieved or removed. Attributes can be read, created, updated and deleted by the web container as well as our application code. We have methods in the Servlet API to add, modify, retrieve and remove attributes. When an object is added to an attribute in any scope, it is called binding as the object is bound into a scoped attribute with a given name.
  • 11. Page 10Classification: Restricted Parameters vs Attributes • Parameters are read only Strings, attributes are read/write objects. • Parameters are String objects, attributes can be objects of any type.
  • 12. Page 11Classification: Restricted Methods to manipulate parameters • Request: (Request time constant) ServletRequest.getParameter(paramname); ServletRequest.getParameterNames(); • ServletConfig init parameters: (Deployment time constant) ServletConfig.getInitParameterNames() ServletConfig.getInitParameter(String paramName) • ServletContext init parameters: (Deployment time constant) ServletContext.getInitParameterNames() ServletContext.getInitParameter(String paramName) AVAILABLE FOR THE REQUEST AVAILABLE FOR THE SERVLET AVAILABLE FOR THE WHOLE APPLICATION
  • 13. Page 12Classification: Restricted Web.xml : init parameters (Servlet Scope)
  • 14. Page 13Classification: Restricted Web.xml: Init parameters (Application scope)
  • 15. Page 14Classification: Restricted ServletConfig vs ServletContext • ServletConfig // Available for a specific servlet • ServletConfig available in javax.servlet.*; package • ServletConfig object is one per servlet class • Object of ServletConfig will be created during initialization process of the servlet • This Config object is public to a particular servlet only • Scope: As long as a servlet is executing, ServletConfig object will be available, it will be destroyed once the servlet execution is completed. • We should give request explicitly, in order to create ServletConfig object for the first time • In web.xml – <init-param> tag will be appear under <servlet-class> tag • ServletContext // Available for whole application • ServletContext available in javax.servlet.*; package • ServletContext object is global to entire web application • Object of ServletContext will be created at the time of web application deployment • Scope: As long as web application is executing, ServletContext object will be available, and it will be destroyed once the application is removed from the server. • ServletContext object will be available even before giving the first request • In web.xml – <context-param> tag will be appear under <web-app> tag
  • 16. Page 15Classification: Restricted How to get servletContext? getServletConfig( ).getServletContext( ); request.getSession( ).getServletContext( ); getServletContext( ); request.getServletContext();
  • 17. Page 16Classification: Restricted Understanding scope of attributes • Similar to scope and lifetime of variables in Java as you have seen in blocks and methods in java, parameters and attributes in a Java EE web application also have scope and lifetime in the context of the web application. • The scope of a parameter/attribute denotes the availability of that parameter/attribute for use. A web application serves multiple requests from clients when it is up and running. These requests can be from same client or different clients. We have seen from the servlet life cycle that a servlet’s service() method is called every time a request comes.
  • 18. Page 17Classification: Restricted Scoping in Servlets and JSP • Request scope • Session scope • Application or context scope • Page scope (only for JSP)
  • 19. Page 18Classification: Restricted Request Scope • Request scope start from the moment an HTTP request hits a servlet in our web container and end when the servlet is done with delivering the HTTP response. • With respect to the servlet life cycle, the request scope begins on entry to a servlet’s service() method and ends on the exit from that method. • A ‘request’ scope parameter/attribute can be accessed from any of servlets or jsps that are part of serving one request. For example, you call one servlet/jsp, it then calls another servlet/jsp and so on, and finally the response is sent back to the client. • Request scope is denoted by javax.servlet.http.HttpServletRequest interface. • Container passes the request object as an argument of type HttpServletRequest to Servlet's service method. • Request object is available in a JSP page as an implicit object called request. You can set value for an attribute in request object from a servlet and get it from a JSP within the same request using the implicit request object.
  • 20. Page 19Classification: Restricted Session scope • A session scope starts when a client (e.g. browser window) establishes connection with our web application till the point where the browser window is closed. • Session scope spans across multiple requests from the same client. • A notable feature of tabbed browsing is that session is shared between the tabs and hence you can requests from other tabs too during a session without logging in again. For instance, you can load your Gmail inbox in another tab without logging in again. This also means browsing an unknown site and a secure site from different tabs from the same browser can expose your secure session ID to malicious applications. So always open a new browser window when you want to do secure transactions, especially financial transactions. • Session scope is denoted by javax.servlet.http.HttpSession interface. • Session object is available in a JSP page as an implicit object called session. • In a servlet, you can get Session object by calling request.getSession().
  • 21. Page 20Classification: Restricted Application or context scope • Context scope or application scope starts from the point where a web application is put into service (started) till it is removed from service (shutdown) or the web application is reloaded. Parameters/attributes within the application scope will be available to all requests and sessions. • Application scope is denoted by javax.servlet.ServletContext interface. • Application object is available in a JSP page as an implicit object called application. • In a servlet, you can get application object by calling getServletContext() from within the servlets code directly (the servlet itself implements the ServletConfig interface that contains this method) or by explicitly calling getServletConfig().getServletContext(). • The web container provides one ServletContext object per web application per JVM.
  • 22. Page 21Classification: Restricted Page scope (Only for JSP, not for Servlets) • The page scope restricts the scpoe and lifetime of attributes to the same page where it was created. • Page scope is denoted by javax.servlet.jsp.PageContext abstract class. • It is available in a JSP page as an implicit object called pageScope
  • 23. Page 22Classification: Restricted Servlets – Scope at a glance • Application scope request.getServletContext(); request.getServletContext().setAttribute("attribute_name","value") • Session scope request.getSession(); //going to create the session if session is not exist. request.getSession(false); // Not going to create the session. session.getAttribute("attribute_name"); • Request scope request.setAttribute("attribute_name","value"); request.getAttribute("attribute_name"); // return the Object you have to cast it
  • 24. Java & JEE Training Session tracking with servlets
  • 25. Page 24Classification: Restricted HTTP IS STATELESS CLIENT SERVER LOGIN ID AND PASSWORD LOGIN SUCCESSFUL ENQUIRE ACCOUNT DETAILS I DON’T KNOW YOU. PLEASE LOGIN… SESSION - COOKIES… HOW DO I MAINTAIN SESSIONS?
  • 26. Page 25Classification: Restricted HTTP IS A STATELESS PROTOCOL CLIENT SERVER LOGIN ID AND PASSWORD LOGIN SUCCESSFUL; SESSIONID=1234; ENQUIRE ACCOUNT DETAILS;SESSIONID=1234; I DON’T KNOW YOU. PLEASE LOGIN… SESSION - COOKIES HOW DO I MAINTAIN SESSIONS?
  • 27. Page 26Classification: Restricted Why track sessions? • HTTP is stateless protocol • So we need to maintain state across multiple requests of a session using session tracking techniques. • Session tracking techniques: • Cookies • Hidden Form Field • URL Rewriting • HttpSession
  • 29. Page 28Classification: Restricted Using cookies • javax.servlet.http.Cookie class • Creating a cookie: Cookie ck=new Cookie("user",“pawan");//creating cookie object response.addCookie(ck);//adding cookie in the response • Deleting a cookie Cookie ck=new Cookie("user","");//deleting value of cookie ck.setMaxAge(0);//changing the maximum age to 0 seconds response.addCookie(ck);//adding cookie in the response • Get all cookies from request: Cookie ck[]=request.getCookies(); for(int i=0;i<ck.length;i++){ out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing cookies info }
  • 31. Page 30Classification: Restricted Hidden form fields… • A web server can send a hidden HTML form field along with a unique session ID as follows: <input type="hidden" name="sessionid" value="12345"> • This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web browsers. • Advantage of Hidden Form Field • It will always work whether cookie is disabled or not. • Disadvantage of Hidden Form Field: • It is maintained at server side. • Extra form submission is required on each pages. • Only textual information can be used.
  • 32. Page 31Classification: Restricted URL Rewriting • You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. • For example, with http://mycompany.com/file.htm;sessionid=12345, the session identifier is attached as sessionid=12345 which can be accessed at the web server to identify the client. • URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies but here drawback is that you would have generate every URL dynamically to assign a session ID though page is simple static HTML page. • Advantage of URL Rewriting • It will always work whether cookie is disabled or not (browser independent). • Extra form submission is not required on each pages. • Disadvantage of URL Rewriting • It will work only with links. • It can send Only textual information.
  • 33. Page 32Classification: Restricted Using HttpSession • HttpSession object is used to store entire session with a specific client. We can store, retrieve and remove attribute from HttpSession object. Any servlet can have access to HttpSession object throughout the getSession() method of the HttpServletRequest object.
  • 34. Page 33Classification: Restricted Important HttpSession Methods Methods Description long getCreationTime() returns the time when the session was created, measured in milliseconds since midnight January 1, 1970 GMT. String getId() returns a string containing the unique identifier assigned to the session. long getLastAccessedTime() returns the last time the client sent a request associated with the session int getMaxInactiveInterval() returns the maximum time interval, in seconds. void invalidate() destroy the session boolean isNew() returns true if the session is new else false void setMaxInactiveInterval(int interval) Specifies the time, in seconds,after servlet container will invalidate the session.
  • 36. Page 35Classification: Restricted HttpSession Demo • Demo • Write a login / logout application using HttpSession
  • 37. Page 36Classification: Restricted Topics to be covered in next session • Session tracking with servlets