SlideShare a Scribd company logo
Security
Agenda
• Understanding major security concern
• Declarative v/s programmatic security
• Using form based authentication
• Using BASIC authentication
Understanding major security concern
• Two major components of Web application security
- Authentication
- Authorization
Understanding major security concern
• Preventing unauthorized users from accessing sensitive data
- Access restriction
• Identifying which resources need protection
• Identifying who should have access to them
- Authentication
• Identifying users to determine if they are one of the
authorized ones
• Preventing attackers from stealing network data while it is in transit.
- Encryption (usually with SSL)
Declarative Security
• Servlets or JSP’s need not have any security-aware code
• Security aspects must be handled by the server
- Prevent unauthorized access
• Declare certain URL as protected in web.xml
• Designate authentication method that server uses
- Safeguard network data
• Certain URL should only be accessed with SSL
• If users uses regular HTTP then server should automatically
redirect them to HTTPS(SSL) equivalent
Programmatic Security
• Protected Servlets and JSP pages atleast partially manage their own
security
- Less dependency on server specific setting
• To prevent unauthorized access
- Each Servlets or JSP page must either authenticate
the user or verify that the user has been
authenticate previously
• To safeguard network data
- Each servlet and JSP page has to check the
network protocol used to access it
Web-tier Authentication Schemes
• HTTP basic authentication based
- with or without SSL
• Form-based authentication based
- with or without SSL
• Client-certificate authentication based
- Has to use SSL
• Digest authentication based
- Does not need to use SSL
HTTP Basic Authentication
• Web server collects user identification (user name and password)
through a browser provided dialog box
• Not secure since user name and password are in “easily decodable”
form over the wire
- Encoding scheme is Base64
- Someone can easily decode it
- Not encrypted
Steps for Basic Authentication
1. Set up username, passwords, and roles (realms)
2. Tell web container that you are using Basic authentication
3. Specify which URLs (web resources) should be access-
controlled (password-protected)
Steps for Setting up realms
• <install-dir>/conf/tomcat-users.xml
• Unencrypted: not secure but easy to set up and maintain
<?xml version='1.0'?>
<tomcat-users>
<role rolename="manager"/>
<role rolename="employee"/>
<role rolename="admin"/>
<user username="sang" password="sangPassword"
roles="manager,employee"/>
</tomcat-users>
Step II: Tell your application
• In web.xml file of your web application
<web-app>
...
<security-constraint>...</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>realm name</realm-name>
</login-config>
...
</web-app>
Form based Authentication
• Web application collects user identification (user name, password,
and other information) through a custom login page
• Not secure since user name and password are in “easily decodable”
form over the wire
- Encoding scheme is Base64
- Someone can easily decode it
- Not encrypted
Authentication Flow
Steps to configure Form Based
Authentication
1. Set up username, passwords, and roles (realms)
2. Tell web container that you are using Form-based
authentication
3. Create custom “Login page”
4. Create custom “Login failure error page”
5. Specify which URLs (web resources) should be access-
controlled (password-protected)
Step I : Setting up realms
• <install-dir>/conf/tomcat-users.xml
• Unencrypted: not secure but easy to set up and maintain
<?xml version='1.0'?>
<tomcat-users>
<role rolename="manager"/>
<role rolename="employee"/>
<role rolename="admin"/>
<user username="sang" password="sangPassword"
roles="manager,employee"/>
</tomcat-users>
Step II: Tell your application
• In web.xml file of your web application
<web-app>
...
<security-constraint>...</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<realm-name>realm name</realm-name>
</login-config>
...
</web-app>
Step IV: Create Login Failure page
• Can be HTML or JSP page
• No specific content is mandated
Step III: Create a custom Login page
• Can be HTML or JSP page
• Contains HTML form like following
<FORM ACTION="j_security_check"
METHOD="POST">
…
<INPUT TYPE="TEXT" NAME="j_username">
…
<INPUT TYPE="PASSWORD" NAME="j_password">
…
</FORM>
Summary
• Main security issues
- Preventing access by unauthorized user
- Preventing attackers from stealing network data
• Declarative security
- Much less work than programmatic security
- Requires server-specific password setup
• Form-based authentication
- Attempts to access restricted resources get redirected to login page. HTML
form gathers username and password.Session tracking tracks authenticated
users.
• BASIC authentication
- Attempts to access restricted resources results in dialog box. Dialog gathers
username and password. HTTP headers track authenticated users.
Understanding Listeners
• JSP is a template page technology
- High level abstraction of Servlets
• Separation of presentation from logic
• Even non java programmer can create JSP pages with reasonable ease
Available Listeners
• Servlet context listeners.
- These listeners are notified when the servlet context (i.e.,the
Web application) is initialized and destroyed.
• Servlet context attribute listeners.
- These listeners are notified when attributes are added
to,removed from, or replaced in the servlet context.
• Session listeners.
- These listeners are notified when session objects are
created, invalidated, or timed out.
• Session attribute listeners.
- These listeners are notified when attributes are added to,
removed from, or replaced in any session.
Creating a Listeners
• Implement the appropriate interface.
- Use ServletContextListener, ServletContextAttributeListener,
- HttpSessionListener, or HttpSessionAttributeListener.
• Override the methods needed to respond to the events of interest.
- Provide empty bodies for the other methods in the interface.
• Access the important Web application objects.
- Six objects that you are likely to use in event-handling methods:
• The servlet context
• The name of the servlet context attribute that changed
• The value of the servlet context attribute that changed
• The session object
• The name of the session attribute that changed
Creating a Listeners
• Use these objects.
- This process is application specific, but there are some common themes.
For example, with the servlet context, you are most likely to read
initialization parameters getInitParameter), store data for later access
(setAttribute), and read previously stored data (getAttribute).
• Declare the listener.
- You do this with the listener and listener-class elements of the general
Web application deployment descriptor (web.xml) or of a tag library
descriptor file.
• Provide any needed initialization parameters.
- Servlet context listeners commonly read context initialization
parameters to use as the basis of data that is made available to all servlets
and JSP ages. You use the context-param web.xml element to provide the
Monitoring Creation and Destruction
• The ServletContextListener class responds to the Initialization
and destruction of the servlet context.
- These events correspond to the creation and
shutdown of the Web application itself.
• ServletContextListener is most commonly used to
- Set up application-wide resources like database
connection pools
- Read the initial values of application-wide data that
will be used by multiple servlets and JSP pages.
Implementing ServletContextListener
• Implement the ServletContextListener interface.
• Override contextInitialized and contextDestroyed.
- contextInitialized is triggered when the Web application is first loaded and the
servlet context is created. Most common tasks:
• Creating application-wide data (e.g., by reading context init params)
• Storing that data in an easily accessible location .
- contextDestroyed is triggered when the Web application is being shut down
and the servlet context is about to be destroyed. Most common task:
• Releasing resources (e.g. closing connections).
• Obtain a reference to the servlet context.
- The contextInitialized and contextDestroyed methods each take a
ServletContextEvent as an argument.
- The ServletContextEvent class has a getServletContext method that returns the servlet context
Implementing ServletContextListener
• Use the servlet context.
- Read initialization parameters: getInitParameter
- Store data:setAttribute
- Make log file entries: log.
• Declare the listener.
<listener>
<listener-class>package.Listener</listener-class>
</listener>
• Provide needed initialization parameters.
<context-param>
<param-name>name</param-name>
<param-value>value</param-value>
</context-param>
Implementing ServletContextAttributeListener
• Implement ServletContextAttributeListener
• Override attributeAdded, attributeReplaced, and attributeRemoved.
- attributeAdded is triggered when a new attribute name is first added to the
servlet context.
- attributeReplaced is triggered when a new value is assigned to an existing
name. attributeAdded is not triggered in this case. The old value is
obtained via event.getValue and the new value is obtained via context.
- getAttribute. attributeRemoved is triggered when a servlet context attribute
is removed altogether.
• Obtain references to the attribute name, attribute value, and servlet
context.
- Call the following methods of the event object: getName,getValue, and
getServletContext
Implementing
ServletContextAttributeListener
• Use the objects.
- You normally compare attribute name to a stored name to see if it is the one you are
monitoring. The attribute value is used in an application-specific manner. The
servlet context is usually used to read previously stored attributes (getAttribute),
store new or changed attributes (setAttribute), and make entries in the log file (log).
• Declare the listener.
- Use the listener and listener-class elements to list the fully qualified name of the
listener class,
<listener>
<listener-class>
somePackage.SomeListener
</listener-class>
</listener>
Recognizing Session Creation and destruction
• Implement the HttpSessionListener interface.
• Override sessionCreated and sessionDestroyed.
- sessionCreated is triggered when a new session is created.
- sessionDestroyed is triggered when a a session is destroyed. This destruction
could be due to an explicit call to the invalidate method or because the elapsed
time since the last client access exceeds the session timeout.
- Multithreaded access is possible. Synchronize if necessary.
• Obtain a reference to the session and possibly to the servlet context.
- Each of the two HttpSessionListener methods takes an HttpSessionEvent as
an argument. The HttpSessionEvent class has a getSession method that
provides access to the session object.You almost always want this reference;
you occasionally also want a reference to the servlet context. If so, first obtain
the session object and then call getServletContext on it
Recognizing Session Creation and destruction
• Use the objects.
- One of the only methods you usually call on the session is setAttribute. Do this in
sessionCreated if you want to guarantee that all sessions have a certain attribute.
- Wait! What about getAttribute? Nope. In sessionCreated, there is nothing in the session
yet, so getAttribute is pointless. In addition, all attributes are removed before
sessionDestroyed is called, so calling getAttribute is also pointless there. If you want to
clean up attributes that are left in sessions that time out, you use the attributeRemoved
method of HttpSessionAttributeListener. So, sessionDestroyed is mostly reserved for
listeners that are simply keeping track of the number of sessions in use.
• Declare the listener.
- In web.xml or the TLD file, use listener and listener-class to list fully qualified name of
listener class, as below.
<listener>
<listener-class>package.SomeListener</listener-class>
</listener>
Using HttpSessionAttributeListener
• Implement HttpSessionAttributeListener.
• Override attributeAdded, attributeReplaced, and attributeRemoved.
- attributeAdded is triggered when a new attribute name is first added to a
session.
- attributeReplaced is triggered when a new value is assigned to an
existing name. attributeAdded is not triggered in this case. The old value
is obtained via event.getValue and the new value is obtained via
session.getAttribute.
- attributeRemoved is triggered when a session attribute is removed
altogether. This removal can be due to an explicit programmer call to
removeAttribute, but is more commonly due to the system removing all
attributes of sessions that are about to be deleted because their timeout
expired.
Using HttpSessionAttributeListener
• Obtain references to the attribute name, attribute value, session, & ServletContext.
- The HttpSessionAttributeListener methods take an HttpSessionBindingEvent as
args. HttpSessionBindingEvent has three useful methods: getName (name of
attribute that was changed), getValue (value of changed attribute—new value for
attributeAdded and previous value for attribute Replaced and attributeRemoved),
and getSession (the HttpSession object). If you want access to the servlet context,
first obtain the session and then call getServletContext on it.
• Use the objects.
- The attribute name is usually compared to a stored name to see if it is the one you
are monitoring. The attribute value is used in an application-specific manner. The
session is usually used to read previously stored attributes (getAttribute) or to store
new or changed attributes (setAttribute).
• Declare the listener.
- Use listener and listener-class in web.xml as before. `
Summary of Listeners
- Servlet context listeners.
• Notified when servlet context is initialized and destroyed.
- Servlet context attribute Listeners.
• Notified when context attributes are added/removed/replaced
- Session listeners.
• Notified when sessions are created, invalidated, or timed out.
- Session attribute listeners.
• Notified when session attributes are added/removed/replaced

More Related Content

PDF
Cache Security- The Basics
PDF
Cache Security- Configuring a Secure Environment
PDF
Secure Search - Using Apache Sentry to Add Authentication and Authorization S...
PPTX
Session And Cookies In Servlets - Java
PDF
The Unintended Risks of Trusting Active Directory
PDF
Hive contributors meetup apache sentry
PPTX
01 session tracking
PDF
Shield talk elasticsearch meetup Zurich 27.05.2015
Cache Security- The Basics
Cache Security- Configuring a Secure Environment
Secure Search - Using Apache Sentry to Add Authentication and Authorization S...
Session And Cookies In Servlets - Java
The Unintended Risks of Trusting Active Directory
Hive contributors meetup apache sentry
01 session tracking
Shield talk elasticsearch meetup Zurich 27.05.2015

What's hot (20)

PDF
Attacking and Defending Kubernetes - Nithin Jois
PDF
A Novel methodology for handling Document Level Security in Search Based Appl...
PPTX
Deep dive into Java security architecture
PPTX
Design Practices for a Secure Azure Solution
PDF
Advanced Java
PDF
Keystone: Federated
PDF
State of Solr Security 2016: Presented by Ishan Chattopadhyaya, Lucidworks
PPTX
Security Architecture of the Java Platform (BG OUG, Plovdiv, 13.06.2015)
PPTX
Introduction to ASP.Net Viewstate
PDF
Asp.net state management
PPTX
Servlets
PDF
aclpwn - Active Directory ACL exploitation with BloodHound
PPT
Java Servlets
PPTX
WMI for Penetration Testers - Arcticcon 2017
PDF
OpenStack Identity - Keystone (liberty) by Lorenzo Carnevale and Silvio Tavilla
PPT
SQL injection basics
PDF
AAI 2236-Using the New Java Concurrency Utilities with IBM WebSphere
PDF
4 Basic PHP
PPTX
OpenStack Keystone
Attacking and Defending Kubernetes - Nithin Jois
A Novel methodology for handling Document Level Security in Search Based Appl...
Deep dive into Java security architecture
Design Practices for a Secure Azure Solution
Advanced Java
Keystone: Federated
State of Solr Security 2016: Presented by Ishan Chattopadhyaya, Lucidworks
Security Architecture of the Java Platform (BG OUG, Plovdiv, 13.06.2015)
Introduction to ASP.Net Viewstate
Asp.net state management
Servlets
aclpwn - Active Directory ACL exploitation with BloodHound
Java Servlets
WMI for Penetration Testers - Arcticcon 2017
OpenStack Identity - Keystone (liberty) by Lorenzo Carnevale and Silvio Tavilla
SQL injection basics
AAI 2236-Using the New Java Concurrency Utilities with IBM WebSphere
4 Basic PHP
OpenStack Keystone
Ad

Similar to Advance java session 19 (20)

PPTX
Advance java session 18
PPTX
SCWCD : Secure web : CHAP : 7
PPTX
SCWCD : Secure web
PPTX
SCWCD : The servlet container : CHAP : 4
PDF
Bt0083 server side programing 2
PPTX
Spring security
PPTX
1 GTU Unit 3 Listeners and Filters.pptx
PDF
Spring security4.x
PPT
Listeners and filters in servlet
PDF
Advancedservletsjsp
PPT
Session 2 servlet context and session tracking - Giáo trình Bách Khoa Aptech
PPTX
Spring Security services for web applications
PPT
Spring Security Introduction
PPTX
AJppt.pptx
PDF
JavaCro'14 - Securing web applications with Spring Security 3 – Fernando Redo...
PDF
Introduction tomcat7 servlet3
PPT
Web Apps Security
PDF
Servlet to Spring: Internal Understanding
PPTX
Request dispacther interface ppt
PPT
Intro to Web Application Security
Advance java session 18
SCWCD : Secure web : CHAP : 7
SCWCD : Secure web
SCWCD : The servlet container : CHAP : 4
Bt0083 server side programing 2
Spring security
1 GTU Unit 3 Listeners and Filters.pptx
Spring security4.x
Listeners and filters in servlet
Advancedservletsjsp
Session 2 servlet context and session tracking - Giáo trình Bách Khoa Aptech
Spring Security services for web applications
Spring Security Introduction
AJppt.pptx
JavaCro'14 - Securing web applications with Spring Security 3 – Fernando Redo...
Introduction tomcat7 servlet3
Web Apps Security
Servlet to Spring: Internal Understanding
Request dispacther interface ppt
Intro to Web Application Security
Ad

More from Smita B Kumar (19)

PPTX
Advance java session 20
PPTX
Advance java session 17
PPTX
Advance java session 16
PPTX
Advance java session 15
PPTX
Advance java session 14
PPTX
Advance java session 13
PPTX
Advance java session 12
PPTX
Advance java session 11
PPTX
Advance java session 10
PPTX
Advance java session 9
PPTX
Advance java session 8
PPTX
Advance java session 7
PPTX
Advance java session 6
PPTX
Advance java session 5
PPTX
Advance java session 4
PPTX
Advance java session 3
PPTX
Advance java session 2
PPTX
JEE session 1
PPTX
01 introduction to struts2
Advance java session 20
Advance java session 17
Advance java session 16
Advance java session 15
Advance java session 14
Advance java session 13
Advance java session 12
Advance java session 11
Advance java session 10
Advance java session 9
Advance java session 8
Advance java session 7
Advance java session 6
Advance java session 5
Advance java session 4
Advance java session 3
Advance java session 2
JEE session 1
01 introduction to struts2

Recently uploaded (20)

PPTX
Big Data Technologies - Introduction.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Approach and Philosophy of On baking technology
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Cloud computing and distributed systems.
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
Big Data Technologies - Introduction.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
The AUB Centre for AI in Media Proposal.docx
Spectral efficient network and resource selection model in 5G networks
Programs and apps: productivity, graphics, security and other tools
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
MIND Revenue Release Quarter 2 2025 Press Release
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Approach and Philosophy of On baking technology
Advanced methodologies resolving dimensionality complications for autism neur...
Review of recent advances in non-invasive hemoglobin estimation
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Encapsulation_ Review paper, used for researhc scholars
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Cloud computing and distributed systems.
Diabetes mellitus diagnosis method based random forest with bat algorithm

Advance java session 19

  • 2. Agenda • Understanding major security concern • Declarative v/s programmatic security • Using form based authentication • Using BASIC authentication
  • 3. Understanding major security concern • Two major components of Web application security - Authentication - Authorization
  • 4. Understanding major security concern • Preventing unauthorized users from accessing sensitive data - Access restriction • Identifying which resources need protection • Identifying who should have access to them - Authentication • Identifying users to determine if they are one of the authorized ones • Preventing attackers from stealing network data while it is in transit. - Encryption (usually with SSL)
  • 5. Declarative Security • Servlets or JSP’s need not have any security-aware code • Security aspects must be handled by the server - Prevent unauthorized access • Declare certain URL as protected in web.xml • Designate authentication method that server uses - Safeguard network data • Certain URL should only be accessed with SSL • If users uses regular HTTP then server should automatically redirect them to HTTPS(SSL) equivalent
  • 6. Programmatic Security • Protected Servlets and JSP pages atleast partially manage their own security - Less dependency on server specific setting • To prevent unauthorized access - Each Servlets or JSP page must either authenticate the user or verify that the user has been authenticate previously • To safeguard network data - Each servlet and JSP page has to check the network protocol used to access it
  • 7. Web-tier Authentication Schemes • HTTP basic authentication based - with or without SSL • Form-based authentication based - with or without SSL • Client-certificate authentication based - Has to use SSL • Digest authentication based - Does not need to use SSL
  • 8. HTTP Basic Authentication • Web server collects user identification (user name and password) through a browser provided dialog box • Not secure since user name and password are in “easily decodable” form over the wire - Encoding scheme is Base64 - Someone can easily decode it - Not encrypted
  • 9. Steps for Basic Authentication 1. Set up username, passwords, and roles (realms) 2. Tell web container that you are using Basic authentication 3. Specify which URLs (web resources) should be access- controlled (password-protected)
  • 10. Steps for Setting up realms • <install-dir>/conf/tomcat-users.xml • Unencrypted: not secure but easy to set up and maintain <?xml version='1.0'?> <tomcat-users> <role rolename="manager"/> <role rolename="employee"/> <role rolename="admin"/> <user username="sang" password="sangPassword" roles="manager,employee"/> </tomcat-users>
  • 11. Step II: Tell your application • In web.xml file of your web application <web-app> ... <security-constraint>...</security-constraint> <login-config> <auth-method>BASIC</auth-method> <realm-name>realm name</realm-name> </login-config> ... </web-app>
  • 12. Form based Authentication • Web application collects user identification (user name, password, and other information) through a custom login page • Not secure since user name and password are in “easily decodable” form over the wire - Encoding scheme is Base64 - Someone can easily decode it - Not encrypted
  • 14. Steps to configure Form Based Authentication 1. Set up username, passwords, and roles (realms) 2. Tell web container that you are using Form-based authentication 3. Create custom “Login page” 4. Create custom “Login failure error page” 5. Specify which URLs (web resources) should be access- controlled (password-protected)
  • 15. Step I : Setting up realms • <install-dir>/conf/tomcat-users.xml • Unencrypted: not secure but easy to set up and maintain <?xml version='1.0'?> <tomcat-users> <role rolename="manager"/> <role rolename="employee"/> <role rolename="admin"/> <user username="sang" password="sangPassword" roles="manager,employee"/> </tomcat-users>
  • 16. Step II: Tell your application • In web.xml file of your web application <web-app> ... <security-constraint>...</security-constraint> <login-config> <auth-method>FORM</auth-method> <realm-name>realm name</realm-name> </login-config> ... </web-app>
  • 17. Step IV: Create Login Failure page • Can be HTML or JSP page • No specific content is mandated
  • 18. Step III: Create a custom Login page • Can be HTML or JSP page • Contains HTML form like following <FORM ACTION="j_security_check" METHOD="POST"> … <INPUT TYPE="TEXT" NAME="j_username"> … <INPUT TYPE="PASSWORD" NAME="j_password"> … </FORM>
  • 19. Summary • Main security issues - Preventing access by unauthorized user - Preventing attackers from stealing network data • Declarative security - Much less work than programmatic security - Requires server-specific password setup • Form-based authentication - Attempts to access restricted resources get redirected to login page. HTML form gathers username and password.Session tracking tracks authenticated users. • BASIC authentication - Attempts to access restricted resources results in dialog box. Dialog gathers username and password. HTTP headers track authenticated users.
  • 20. Understanding Listeners • JSP is a template page technology - High level abstraction of Servlets • Separation of presentation from logic • Even non java programmer can create JSP pages with reasonable ease
  • 21. Available Listeners • Servlet context listeners. - These listeners are notified when the servlet context (i.e.,the Web application) is initialized and destroyed. • Servlet context attribute listeners. - These listeners are notified when attributes are added to,removed from, or replaced in the servlet context. • Session listeners. - These listeners are notified when session objects are created, invalidated, or timed out. • Session attribute listeners. - These listeners are notified when attributes are added to, removed from, or replaced in any session.
  • 22. Creating a Listeners • Implement the appropriate interface. - Use ServletContextListener, ServletContextAttributeListener, - HttpSessionListener, or HttpSessionAttributeListener. • Override the methods needed to respond to the events of interest. - Provide empty bodies for the other methods in the interface. • Access the important Web application objects. - Six objects that you are likely to use in event-handling methods: • The servlet context • The name of the servlet context attribute that changed • The value of the servlet context attribute that changed • The session object • The name of the session attribute that changed
  • 23. Creating a Listeners • Use these objects. - This process is application specific, but there are some common themes. For example, with the servlet context, you are most likely to read initialization parameters getInitParameter), store data for later access (setAttribute), and read previously stored data (getAttribute). • Declare the listener. - You do this with the listener and listener-class elements of the general Web application deployment descriptor (web.xml) or of a tag library descriptor file. • Provide any needed initialization parameters. - Servlet context listeners commonly read context initialization parameters to use as the basis of data that is made available to all servlets and JSP ages. You use the context-param web.xml element to provide the
  • 24. Monitoring Creation and Destruction • The ServletContextListener class responds to the Initialization and destruction of the servlet context. - These events correspond to the creation and shutdown of the Web application itself. • ServletContextListener is most commonly used to - Set up application-wide resources like database connection pools - Read the initial values of application-wide data that will be used by multiple servlets and JSP pages.
  • 25. Implementing ServletContextListener • Implement the ServletContextListener interface. • Override contextInitialized and contextDestroyed. - contextInitialized is triggered when the Web application is first loaded and the servlet context is created. Most common tasks: • Creating application-wide data (e.g., by reading context init params) • Storing that data in an easily accessible location . - contextDestroyed is triggered when the Web application is being shut down and the servlet context is about to be destroyed. Most common task: • Releasing resources (e.g. closing connections). • Obtain a reference to the servlet context. - The contextInitialized and contextDestroyed methods each take a ServletContextEvent as an argument. - The ServletContextEvent class has a getServletContext method that returns the servlet context
  • 26. Implementing ServletContextListener • Use the servlet context. - Read initialization parameters: getInitParameter - Store data:setAttribute - Make log file entries: log. • Declare the listener. <listener> <listener-class>package.Listener</listener-class> </listener> • Provide needed initialization parameters. <context-param> <param-name>name</param-name> <param-value>value</param-value> </context-param>
  • 27. Implementing ServletContextAttributeListener • Implement ServletContextAttributeListener • Override attributeAdded, attributeReplaced, and attributeRemoved. - attributeAdded is triggered when a new attribute name is first added to the servlet context. - attributeReplaced is triggered when a new value is assigned to an existing name. attributeAdded is not triggered in this case. The old value is obtained via event.getValue and the new value is obtained via context. - getAttribute. attributeRemoved is triggered when a servlet context attribute is removed altogether. • Obtain references to the attribute name, attribute value, and servlet context. - Call the following methods of the event object: getName,getValue, and getServletContext
  • 28. Implementing ServletContextAttributeListener • Use the objects. - You normally compare attribute name to a stored name to see if it is the one you are monitoring. The attribute value is used in an application-specific manner. The servlet context is usually used to read previously stored attributes (getAttribute), store new or changed attributes (setAttribute), and make entries in the log file (log). • Declare the listener. - Use the listener and listener-class elements to list the fully qualified name of the listener class, <listener> <listener-class> somePackage.SomeListener </listener-class> </listener>
  • 29. Recognizing Session Creation and destruction • Implement the HttpSessionListener interface. • Override sessionCreated and sessionDestroyed. - sessionCreated is triggered when a new session is created. - sessionDestroyed is triggered when a a session is destroyed. This destruction could be due to an explicit call to the invalidate method or because the elapsed time since the last client access exceeds the session timeout. - Multithreaded access is possible. Synchronize if necessary. • Obtain a reference to the session and possibly to the servlet context. - Each of the two HttpSessionListener methods takes an HttpSessionEvent as an argument. The HttpSessionEvent class has a getSession method that provides access to the session object.You almost always want this reference; you occasionally also want a reference to the servlet context. If so, first obtain the session object and then call getServletContext on it
  • 30. Recognizing Session Creation and destruction • Use the objects. - One of the only methods you usually call on the session is setAttribute. Do this in sessionCreated if you want to guarantee that all sessions have a certain attribute. - Wait! What about getAttribute? Nope. In sessionCreated, there is nothing in the session yet, so getAttribute is pointless. In addition, all attributes are removed before sessionDestroyed is called, so calling getAttribute is also pointless there. If you want to clean up attributes that are left in sessions that time out, you use the attributeRemoved method of HttpSessionAttributeListener. So, sessionDestroyed is mostly reserved for listeners that are simply keeping track of the number of sessions in use. • Declare the listener. - In web.xml or the TLD file, use listener and listener-class to list fully qualified name of listener class, as below. <listener> <listener-class>package.SomeListener</listener-class> </listener>
  • 31. Using HttpSessionAttributeListener • Implement HttpSessionAttributeListener. • Override attributeAdded, attributeReplaced, and attributeRemoved. - attributeAdded is triggered when a new attribute name is first added to a session. - attributeReplaced is triggered when a new value is assigned to an existing name. attributeAdded is not triggered in this case. The old value is obtained via event.getValue and the new value is obtained via session.getAttribute. - attributeRemoved is triggered when a session attribute is removed altogether. This removal can be due to an explicit programmer call to removeAttribute, but is more commonly due to the system removing all attributes of sessions that are about to be deleted because their timeout expired.
  • 32. Using HttpSessionAttributeListener • Obtain references to the attribute name, attribute value, session, & ServletContext. - The HttpSessionAttributeListener methods take an HttpSessionBindingEvent as args. HttpSessionBindingEvent has three useful methods: getName (name of attribute that was changed), getValue (value of changed attribute—new value for attributeAdded and previous value for attribute Replaced and attributeRemoved), and getSession (the HttpSession object). If you want access to the servlet context, first obtain the session and then call getServletContext on it. • Use the objects. - The attribute name is usually compared to a stored name to see if it is the one you are monitoring. The attribute value is used in an application-specific manner. The session is usually used to read previously stored attributes (getAttribute) or to store new or changed attributes (setAttribute). • Declare the listener. - Use listener and listener-class in web.xml as before. `
  • 33. Summary of Listeners - Servlet context listeners. • Notified when servlet context is initialized and destroyed. - Servlet context attribute Listeners. • Notified when context attributes are added/removed/replaced - Session listeners. • Notified when sessions are created, invalidated, or timed out. - Session attribute listeners. • Notified when session attributes are added/removed/replaced