Servlet Development Guide : PART III Programming : Chapter 6 The Servlet API : Implementing a Listener
Implementing a Listener
The role of a listener is to receive an event and to act upon that event. A listener does not have access to a request object or a response object. A listener is typically stateless. Instead, a listener receives an event and responds to the event directly.
For example, a session listener can add a specific attribute to each session created within a context. The code sample below implements a listener that initializes each new session with an IsAdministrator attribute.
 
#include <rwsf/servlet/http/HttpSessionListener.h>
#include <rwsf/servlet/http/HttpSessionEvent.h>
#include <rwsf/servlet/http/HttpSession.h>
#include <rwsf/core/Attribute.h>
 
class MyListener : public rwsf::HttpSessionListener {
public:
void sessionCreated(const rwsf::HttpSessionEvent& evt)
{
rwsf::HttpSession session = evt.getSession(); // 1
rwsf::Attribute attr; // 2
attr << false; // 3
session.setAttribute("IsAdministrator", attr); // 4
}
};
RWSF_DEFINE_LISTENER(MyListener)
//1 Extracts the new session from the session event.
//2 Constructs a new, empty rwsf::Attribute.
//3 Copies the value false into the attribute.
//4 Adds the attribute to the session with the name IsAdministrator.
Creating the attribute in a session listener guarantees that every session in the context contains an IsAdministrator attribute which is initially false. Similar code could be included in each servlet in the application each time the servlet receives a new session. However, isolating the code in a listener simplifies the servlets.