What is listener class in java

Servlet – Event and Listener

The term “event” refers to the occurrence of something. An event occurs when the state of an object changes. When these exceptions occur, we can conduct certain crucial actions, such as collecting total and current logged-in users, establishing database tables when deploying the project, building database connection objects, and so on. The javax.servlet and javax.servlet.http packages contain numerous Event classes and Listener interfaces.

The primary function of a Listener in a GUI application is to concentrate an event from a specific GUI component, handle it using Listener functions, and provide the response to the GUI application. The following technique is referred to as Event Handling or Event Delegation Model in GUI applications.

Event Categories

Servlet events are divided into two categories: high-level and low-level.

  1. Servlet context-level (application-level) event: This event concerns resources or states held at the appliance servlet context object’s extent.
  2. Session-level event: It involves resources or states associated with a sequence of requests from a single user session; in other words, it is associated with the HTTP session object.

There are two types of events on each of those two levels:

For each of the four-event categories, we can define one or more event listener classes. Multiple event categories can be monitored by a single listener class. Implementing an interface or interfaces from the javax.servlet package or javax.servlet.http package is a common way to make an occasion class.

Читайте также:  Catching all javascript errors

Event Listener Interfaces

Steps for Using Listeners

If we want to utilize listener listeners in our web apps, we must follow the steps below:

Step 1: Get the Listener class ready.

Take one user-defined class, which must be a Listener interface implementation class. For instance, consider the public class Listener is implemented by MyListener

Step 2: In the web.xml file, configure the Listener class.

The following XML tags must be used in the web.xml file to configure the Listener class:

  …… Name of the Listener class  …… 

Except for HttpSessionBindingListener and HttpSessionActivationListener, all Listeners require the aforementioned listener configuration.

1) Methods for ServletContextListeners and the ServletContextEvent Class

The following methods are defined by ServletContextListener:

When a web application is deployed on the server, the ServletContextEvent is informed. It includes the technique shown below, which your listener might call:

ServletContext getServletContext(): This method retrieves the servlet context object that was created or is going to be deleted, from which you may get any information you want.

2) Methods for ServletContextAttributeListener and the ServletContextAttributeEvent Class

ServletContextAttributeListener specifies the following methods:

The event class ServletContextAttributeEvent is used to notify about changes to the attributes of a web application’s servlet context. It includes the techniques listed below, which your listener can use:

  1. String getName() returns the name of the attribute that was added, deleted, or replaced as a string.
  2. Object getValue() is a method for retrieving the value of an attribute that has been added, deleted, or replaced. This method returns the previous value, not the new value, in the event of a replaced attribute.

3) Methods for HttpSessionListeners and the HttpSessionEvent Class

HttpSessionListener specifies the following methods:

When the session object is modified, HttpSessionEvent is informed. It includes the technique shown below, which your listener might call:

HttpSession getSession(): This function is used to obtain the generated or deleted session object.

4) Methods for HttpSessionAttributeListener and the HttpSessionBindingEvent Class

HttpSessionAttributeListener specifies the following methods:

When an object implements HttpSessionBindingListener is bound or freed from a session, HttpSessionBindingEvent is delivered to that object, or to a HttpSessionAttributeListener that has been set in the deployment descriptor when any attribute is bound, unbound, or replaced in a session. It includes the techniques listed below, which your listener can use:

  1. String getName(): returns the name of the attribute that was added, deleted, or replaced as a string.
  2. Object getValue(): is a method for retrieving the value of an attribute that has been added, deleted, or replaced. This method returns the previous value, not the new value, in the event of a replaced attribute.
  3. HttpSession getSession(): This method is used to obtain the session object whose attribute has changed.

Example

To demonstrate the servlet listener in action, let’s create a basic web application. In Eclipse, we’ll build a dynamic web project called ServletListenerExample, and the project structures will look like this.

The context init params and listener settings will be defined in web.xml. The class for database connectivity is DatabaseManager. The object will be added to the servlet context as an attribute. I’ll deal with the session, characteristics, and other things in MyServlet. We’ll use the AppContextListener to read the servlet context init parameters and use them to create the DatabaseManager object, which we’ll then set as an attribute on the ServletContext object. ServletContextAttributeListener is a simple implementation for logging the event when an attribute in the servlet context is added, removed, or replaced. HttpSessionListener is a simple implementation to log the event when the session is created or destroyed. ServletRequestListener is to log the servletRequest IP address when the request is initialized and destroyed.

Источник

Introduction to Event Listeners

If you have read any of the component how-to pages, you probably already know the basics of event listeners.

Let us look at one of the simplest event handling examples possible. It is called Beeper, and it features a button that beeps when you click it.

Click the Launch button to run Beeper using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.

A Click Me Beeper Button

You can find the entire program in Beeper.java . Here is the code that implements the event handling for the button:

public class Beeper . implements ActionListener < . //where initialization occurs: button.addActionListener(this); . public void actionPerformed(ActionEvent e) < . //Make a beep sound. > >

The Beeper class implements the ActionListener interface, which contains one method: actionPerformed . Since Beeper implements ActionListener , a Beeper object can register as a listener for the action events that buttons fire. Once the Beeper has been registered using the Button addActionListener method, the Beeper ‘s actionPerformed method is called every time the button is clicked.

A More Complex Example

The event model, which you saw at its simplest in the preceding example, is quite powerful and flexible. Any number of event listener objects can listen for all kinds of events from any number of event source objects. For example, a program might create one listener per event source. Or a program might have a single listener for all events from all sources. A program can even have more than one listener for a single kind of event from a single event source.

Multiple listeners can register to be notified of events of a particular type from a particular source. Also, the same listener can listen to notifications from different objects.

Each event is represented by an object that gives information about the event and identifies the event source. Event sources are often components or models, but other kinds of objects can also be event sources.

Whenever you want to detect events from a particular component, first check the how-to section for that component. A list of the component how-to sections is here. The how-to sections give examples of handling the events that you are most likely to care about. In How to Use Color Choosers, for instance, you will find an example of writing a change listener to track when the color changes in the color chooser.

The following example demonstrates that event listeners can be registered on multiple objects and that the same event can be sent to multiple listeners. The example contains two event sources ( JButton instances) and two event listeners. One of the event listeners (an instance of a class called MultiListener ) listens for events from both buttons. When it receives an event, it adds the event’s «action command» (which is set to the text on the button’s label) to the top text area. The second event listener (an instance of a class called Eavesdropper ) listens for events on only one of the buttons. When it receives an event, it adds the action command to the bottom text area.

Try this:

  1. Click the Launch button to run MultiListener using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.
  2. Click the Blah blah blah button. Only the MultiListener object is registered to listen to this button.
  3. Click the You do not say! button. Both the MultiListener object and the Eavesdropper object are registered to listen to this button.

You can find the entire program in MultiListener.java . Here is the code that implements the event handling for the button:

public class MultiListener . implements ActionListener < . //where initialization occurs: button1.addActionListener(this); button2.addActionListener(this); button2.addActionListener(new Eavesdropper(bottomTextArea)); > public void actionPerformed(ActionEvent e) < topTextArea.append(e.getActionCommand() + newline); >> class Eavesdropper implements ActionListener < . public void actionPerformed(ActionEvent e) < myTextArea.append(e.getActionCommand() + newline); >>

In the above code, both MultiListener and Eavesdropper implement the ActionListener interface and register as action listeners using the JButton addActionListener method. Both classes’ implementations of the actionPerformed method are similar: they simply add the event’s action command to a text area.

Источник

Оцените статью