Lesson 3 - Servlet II
Lesson 3 - Servlet II
We have learned that web applications are stateless (by default) if given protocol is HTTP (stateless protocol).
It does not allow or provide data access to previous request during the processing of current request in
the Servlet or JSP.
In stateless web app, there is no way to preserve client data across multiple requests:
Create connection
1 Request 2
Client Server
3 Response 4
Close connection
Stateful Web Application
• A web application that can remember or use the data of previous request during the processing of
current request is a called stateful web application.
• In servlet API, there are different ways of making web application stateful so that it remembers
client data across request from same browser.
Create connection
1 Request 2
Server
Client Identifies the previous
request state through
session management
3 Response 4
Close connection
Introduction to Session Management
Session Management is a mechanism used by the web container to store session information for a
particular user.
Session is a conversional state between client and server, and it can consist of multiple requests and
responses between client and server. Sessions are used for maintaining user specific state, including
persistent objects.
User Session: It refers to a series of user application interactions that are tracked by the server.
Types of Session Management
2. URL Writing
3. Cookies
4. HttpSession
Hidden Form Field
Hidden Form • When Server sends response for one particular request, it sends one hidden file attached to it
Field
• Client gets response with one Hidden Field
URL Writing
• In Hidden Field name and value are set
Cookie • If the same page sends request the next time, server can recognize it by getting the parameter
of Hidden Field
One of the limitations of a Hidden Form Field is that it requires extra form
submission on each page.
Using Hidden Form Field to Manage Session
Browser Client
Hidden Form
Field Form 1
Request 1
Name Servlet 1
URL Writing
Address
(Servlet 1 sends a hidden file
with name and attribute)
Cookie
Form 2
Request 2 Servlet 2
HttpSession
Age
(Servlet 2 can get Hidden file
(Hidden file with name and attribute) with name and attribute)
URL Writing
Hidden Form
• In URL writing, one token is appended to URL itself
Field
• This token contains one name and one value
URL Writing
• With the help of hyperlink, token’s name and values are passed to server
• A name and a value is separated using an equal = sign, a parameter name/value pair is
Cookie separated from another parameter using the ampersand(&)
• Code: url?name1=value1&name2=value2&?
HttpSession
Browser Client
Hidden Form
Field Form 1
Request 1
Name Servlet 1
URL Writing
Address
Cookie
Form 2
Url Writing • While creating a cookie, a small amount of information is sent by a Servlet to a web
browser, saved by the browser, and later sent back to the server
• The browser returns cookies to the servlet by adding fields to HTTP request headers
HttpSession
Attributes of a Cookie
Hidden Form
Field • Name: Name of the cookie
• Value: Value of the cookie
Url Writing • Comment: Text explaining purpose of cookie
• Max-Age: Time in seconds after which the client should not send cookie back to server
Hidden Form
Field
Url Writing
Request
Client Server
Response + Cookie
Cookie
Request + Cookie
HttpSession
Constructor and Methods of Cookie Class
Url Writing
• Cookie class has the following methods:
Cookie cookies[]=request.getCoookies();
HttpSession
for(Cookie cookie : cookies)
{
out.print("name = "+ cookie.getName());
out.print("value="+cookie.getValue());
}
Cookie: Limitations
Hidden Form
Field
• All data for a session are kept on the client. Corruption, expiration, or purging of cookie
files can result in incomplete, inconsistent, or missing information.
Url Writing
• Cookies may not be available for many reasons: the user may have disabled them, the
browser version may not support them, the browser may be behind a firewall that filters
Cookie cookies, and so on.
HttpSession
Session Object APIs
Hidden Form • javax.servlet.http.HttpSession interface provides a way to identify one user across more than
Field one page
• Servlet Container uses this interface to create a session between Http Client and Http Server
Url Writing
• Servlet can view and manipulate the information about servlet
• getSession method gets the current valid session associated with this request if create is
false or, if necessary, it creates a new session for the request
HttpSession
HttpSession Methods
Browser
Hidden Form Client
Field Form 1
HttpSession Object
Name Request 1
Url Writing
Address Servlet 1
Set attribute
Cookie value. Example:
request
Form 2 attributes can
HttpSession have name and
Servlet 2 address value
Age Request 2
Advanced Java
DEMO—Session Management in Servlet
Advanced Java
Topic 2—Listeners in Java EE
Change in the state of an object is known as an event, which occurs during the lifecycle of an object.
There are important events related to a web application and Servlets which are handled by event
listener.
To be notified of events, a custom class, that implements the correct listener interface, needs to be
coded and the listener class needs to be deployed via web.xml.
Event Class Servlet APIs
1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextRequestArrtibuteEvent
5. HttpSessionEvent
6. HttpSessionEventBindingEvent
Event Listener Interface
Listeners are objects that notify whenever any event occurs. They contain event processing logics.
ServletContextList
ener • It handles servlet request event
ServletRequestAttr • It notifies when servlet container is initialized and destroys request object
ibuteListener
• Servlet container generates servlet request event when it creates and destroys servlet.request object
ServletContextAttri
butetListener Methods:
HttpSessionActivat
ionListener
Event Listener Interface
ServletRequestList
ener ServletContextListener
ServletContextList
ener
• It handles and processes ServletContextEvent.
ServletRequestAttr • It receives notifications when servlet container creates or destroys context object.
ibuteListener
ServletContextAttri
Methods:
buteListener
void contextInitialized()
HttpSessionListener
void contextDestroyed()
HttpSessionAttribu
teListener
HttpSesionBinding
Listener
HttpSessionActivat
ionListener
Event Listener Interface
ServletRequestList
ener ServletRequestAttributeListener
ServletContextList
ener • It receives notification of ServletRequestAttribute event.
ServletRequestAttr • It is used to find out when an attribute has been added, removed, or replaced from request object.
ibuteListener
Methods:
ServletContextAttri
buteListener void attributeAdded(ServletRequestAttributeEvent srae): Receives notification that an
HttpSessionListener
attribute has been added to the ServletRequest
void attributeRemoved(ServletRequestAttributeEvent srae : Receives notification that an
HttpSessionAttribu
teListener attribute has been removed from the ServletRequest
HttpSesionBinding
void attributeReplaced(ServletRequestAttributeEvent srae): Receives notification that
Listener
an attribute has been replaced on the ServletRequest.
HttpSessionActivat
ionListener
Event Listener Interface
ServletRequestList
ener ServletContextAttributeListener
ServletContextList
ener It receives and processes ServletContextAtrribute event.
ServletRequestAttr
ibuteListener
Methods:
ServletContextAttri
buteListener void attributeAdded(ServletContextAttributeEvent event):
Receives notification that an attribute has been added to the ServletContext.
HttpSessionListener
void attributeRemoved(ServletContextAttributeEvent event):
HttpSessionAttribu Receives notification that an attribute has been removed from the ServletContext.
teListener
void attributeReplaced(ServletContextAttributeEvent event):
HttpSesionBinding
Listener Receives notification that an attribute has been replaced from the ServletContext.
HttpSessionActivat
ionListener
Event Listener Interface
ServletRequestList
ener HttpSessionListener
ServletContextList
ener It receives and processes http session events. This listener is used to find out total active users.
ServletRequestAttr
ibuteListener
Methods:
ServletContextAttri void sessionCreated(HttpSessionEvent se): Receives notification that a session has been
buteListener
created.
HttpSessionListene
r void sessionDestroyed(HttpSessionEvent se): Receives notification that a session is
HttpSesionBinding
Listener
HttpSessionActivat
ionListener
Event Listener Interface
ServletRequestList
ener HttpSessionAttributeListener
ServletContextList
ener • It handles and processes http session binding event.
• It is used to find out when an attribute has been added or replaced from session.
ServletRequestAttr
ibuteListener
Methods:
ServletContextAttri
buteListener void attributeAdded(HttpSessionBindingEvent event): Receives notification that an
HttpSessionActivat
ionListener
Event Listener Interface
ServletRequestList
ener HttpSesionBindingListener
ServletContextList
ener
• It handles and processes http session binding event.
ServletRequestAttr • It notifies when the object of the class has been added or removed from the session.
ibuteListener
ServletContextAttri Methods:
buteListener
HttpSessionActivat
ionListener
Event Listener Interface
ServletRequestList
ener HttpSessionActivationListener
ServletContextList
ener • It receives notification of http session event.
ServletRequestAttr • It notifies when the session migrates from one JVM(Java Virtual Machine) to another.
ibuteListener
Methods:
ServletContextAttri
buteListener
void sessionDidActivate(HttpSessionEvent se) : Notifies that the session has just been activated
HttpSessionListene
r void sessionWillPassivate(HttpSessionEvent se): Notifies that the session is about to be passivated
HttpSessionAttribu
teListener
HttpSesionBinding Application events provide notifications of a change in state of the servlet context (each Web
Listener Application uses its own servlet context) or of an HttpSession object.
HttpSessionActivat
ionListener
Servlet Listener Configuration
@WebListener annotation is used to declare a class as Listener. However, the class should implement
one or more of the Listener interfaces.
<listener>
<listener-class>
packagename.ClassNameOfImplementedListener
</listener-class>
</listener>
Advanced Java
DEMO—Implementing Listener Interface to Handle Events
Advanced Java
Topic 3—Filters in Java EE
• Why Filters?
• What is a Filter?
• Filter in Servlets
Why Filters?
• A filer is an interface used to filter tasks on the request to a resource (a servlet or static content), on the
response from a resource, or both
http request
Filter
request object request object
http response
Filter Types
3. Request-Response Filter: Contains both pre-request processing and post-response generation logic.
Developing and Mapping a Filter Class
<filter>
<filter-name> onelogicalname </filter-name>
<filter-class> filterclassname </filter-class>
</filter>
<filter-mapping>
<filter-name> onelogicalname </filter-name>
<furl-pattern> /urlpatter </url-pattern>
</filter-mapping>
Writing a Filter Program
• Create a Java class to implement Filter interface that has the following three methods:
If multiple filters are configured for servlet, they are executed in the same order in which they are defined in
web.xml
http request
A web application that can remember or use the data of previous request
during the processing of current request is a called stateful web application.
Hidden Form Field, Url Writing, Cookies, and HttpSession are types of session
management.