0% found this document useful (0 votes)
7 views

Lesson 3 - Servlet II

Uploaded by

Prashanth G
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Lesson 3 - Servlet II

Uploaded by

Prashanth G
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Advanced Java

Lesson 3—Java Servlet II

© Simplilearn. All rights reserved.


Learning Objectives

Discuss Session Management

Explain Listeners in Java EE

Describe Filters in Java EE


Advanced Java
Topic 1—Session Management

• Stateless Web Application


• Stateful Web Application
• Session Management and its types
Stateless Web Application

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.

• Making web application stateful is known as session tracking or session management.

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

1. Hidden Form Field

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

HttpSession <input type =”hidden field” name=”somename” value=”somename”/>

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

URL writing works with hyperlinks and sends text information.


URL Writing to Exchange Session Information

Browser Client
Hidden Form
Field Form 1
Request 1
Name Servlet 1
URL Writing
Address

Cookie
Form 2

HttpSession hyperlink Request 2


Servlet 2
Age
url?name1=value1&name2=value2&?
Cookie

Hidden Form • Servlet API provides javax.servlet.http.Cookie class to maintain session


Field
• This class extends Object class and implements Cloneable interface

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

Cookie • Cookie has a name, value, and optional attribute

• 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

Cookie • Domain: Domain to which the cookie should be sent


• Path: The path to which the cookie should be sent
• Secure: Specifies if cookie should be sent via https
HttpSession
Cookies to Exchange Session Information

Hidden Form
Field

Url Writing
Request

Client Server
Response + Cookie
Cookie

Request + Cookie
HttpSession
Constructor and Methods of Cookie Class

• Constructs a cookie with a specified name and value.


Hidden Form
Field public Cookie(java.lang.String name,
java.lang.String value)

Url Writing
• Cookie class has the following methods:

Cookie o getName(): To get the Name of Cookie


o getValue(): To get the value of Cookie
o setMaxAge(): To set maximum age of Cookie
HttpSession
o setValue(): To set value to Cookie
Creating Cookie Object

Code to create Cookie object:


Hidden Form
Field Cookie cookieObj = new Cookie(“name”,”value”);

Code to add Cookie to browser response:


Url Writing
response.addCookie(cookieObj);

Cookie Code to retrieve cookie object:

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

Cookie • javax.servlet.http.HttpSession has method named as getSession

• 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

Returns the maximum time interval, in seconds, that


Hidden Form int getMaxInactiveInterval() the servlet container will keep this session open
Field between client accesses.
Returns a string containing the unique identifier
String getId()
assigned to this session.
Url Writing
void Specifies the time, in seconds, between client requests
setMaxInactiveInterval(int interval) before the servlet container will invalidate this session.
Cookie Invalidates this session and then unbinds any objects
Void invalidate()
bound to it.
Returns the current session associated with this
HttpSession HttpSession getSession() request, or if the request does not have a session, it
creates one.
Returns the current HttpSession associated with this
HttpSession
request or, if there is no current session and create is
getSession(boolean create)
true, it returns a new session.
HttpSession for Session Tracking

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

• Events in Servlet API


• Events Class Servlet API
• Event Listener Interface
Events in Servlet API

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.

Listener Interfaces in servlet APIs are as follows:


1. ServletRequestListener
2. ServletContextListener
3. ServletRequestAttributeListener
4. ServletContextAttributeListener
5. HttpSessionListener
6. HttpSessionAttributeListener
7. HttpSesionBindingListener
8. HttpSessionActivationListener
Event Listener Interface
ServletRequestList
ener ServletRequestListener

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:

HttpSessionListener void requestInitialized(ServletRequestEvent e)


// when Servlet creates request object
HttpSessionAttribu
teListener void requestDestroyed(ServletRequestEvent e)
// When Servlet destroy request object
HttpSesionBinding
Listener

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

HttpSessionAttribu about to be invalidated.


teListener

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

HttpSessionListene attribute has been added to a session


r
void attributeRemoved(HttpSessionBindingEvent event): Receives notification that
HttpSessionAttribu an attribute has been removed from a session
teListener
void attributeReplaced(HttpSessionBindingEvent event): Receives notification that
HttpSesionBinding
Listener
an attribute has been replaced in a session

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

void valueBound(HttpSessionBindingEvent event): Notifies the object that it is


HttpSessionListene
r
being bound to a session and identifies the session.
HttpSessionAttribu void valueUnbound(HttpSessionBindingEvent event): Notifies the object that it
teListener
is being unbound from a session and identifies the session.
HttpSesionBinding
Listener

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.

To define listener in web.xml:

<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?

Filters are used when there is a need:

• For an operation to occur every time a particular request is made


• To perform one operation on other request in the web application
• To allow one operation to be turned off at deployment

The filter API interface can be found in javax.servlet package


What is a Filter?

• 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

• It has 3 methods (lifecycle)

public void init(FilterConfig config);


public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain);
public void destroy();

• Filters are configured in deployment descriptor of a web application


Filter in Servlets

http request

Filter
request object request object

Servlet Container Servlet

response object response object

http response
Filter Types

1. Request Filter: Contains only pre-request processing logic.

2. Response Filter: Contains post-response generation logic.

3. Request-Response Filter: Contains both pre-request processing and post-response generation logic.
Developing and Mapping a Filter Class

Declaring a Filter in the web.xml

<filter>
<filter-name> onelogicalname </filter-name>
<filter-class> filterclassname </filter-class>
</filter>

Mapping a Filter in the web.xml

<filter-mapping>
<filter-name> onelogicalname </filter-name>
<furl-pattern> /urlpatter </url-pattern>
</filter-mapping>
Writing a Filter Program

To write a filter program:

• Create a Java class to implement Filter interface that has the following three methods:

o init() method – It is called once when the container instantiates a filter


o doFilter() method – It is called for every request intercepted by the filter
o destroy() method - Before the web container removes a filter instance from service, the destroy method is called

• Create one web.xml file to configure the filter


Filter Chain

If multiple filters are configured for servlet, they are executed in the same order in which they are defined in
web.xml

http request

request object request object


Servlet Servlet
Container
response object response object

Pre-filter Filter Post-filter


http response
Key Takeaways

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.

Session Management is a mechanism used by the Web container to store session


information for a particular user.

Hidden Form Field, Url Writing, Cookies, and HttpSession are types of session
management.

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.
Quiz
Thank You

You might also like