servlet listeners: ServletRequestAttributeListener

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

Hello, we studied about ServletRequestListener interface in previous post. In this post, we will see how to use ServletRequestAttributeListener can be used to receive notifications whenever some attributes are added, removed or replaced in ServletRequest.

Why is the need?

Sometime we may have a requirement that web application must receive some notifications whenever some attribute is added, removed or replaced in a ServletRequest.

How can we achieve it?

Java EE specification provides an interface called ServletRequestAttributeListener which receives the notifications whenever attributes are added, removed or replaced in a ServletRequest. This interface has three methods.

  • attributeAdded(ServletRequestAttributeEvent event)  : receives notification when an attribute is added in ServletRequest.
  • attributeRemoved(ServletRequestAttributeEvent event)  : receives notification when an attribute is removed from ServletRequest.
  • attributeReplaced(ServletRequestAttributeEvent event) : receives notification when an attribute is removed from ServletRequest.

 

Step 1: Create a dynamic web project

Create a new dynamic web project .

Step 2: Create ServletRequestAttributeListener and configure in web.xml

Create AttributeListener class in your web application as follows.

Configure in web.xml as follows.

 

Step 3: Create HelloServlet.

To listen to attribute change events, we must add, remove and replace them somewhere. Create a HelloServlet which will perform operations on attributes.

Configure HelloServlet in web.xml

 Step 4: Run application.

Now simply deploy the application under tomcat server and start tomcat. Hit url http://localhost:8080/ServletListenerExamples/HelloServlet . You will see the following output.

  •  You can notice here that when attributeReplaced method is called, then the value of attribute is the previous value and not the updated value. This tells that attribute value is replaced after the method completes execution.
  • Also, attributeRemoved method returns the value of attribute name before it is removed.
Share Button

4 comments for “servlet listeners: ServletRequestAttributeListener

  1. November 10, 2013 at 9:02 am

    I cannot thank you enough for the blog article.Really looking forward to read more. Really Cool.

  2. Alex G
    March 2, 2016 at 9:43 am

    I also wanted to thank u for this snippet of code and the others as well. Makes life alot easier with examples that work.

  3. Ajit
    August 12, 2016 at 5:41 pm

    thanks , that’s short , simple and clear 🙂

  4. Raja
    April 18, 2017 at 6:49 pm

    Simple and Nice

Leave a Reply

Your email address will not be published. Required fields are marked *