Home  >  Article  >  Java  >  What is a listener in java

What is a listener in java

little bottle
little bottleOriginal
2019-05-25 16:29:064898browse

A component that monitors the operation of the Web server and takes preset processing measures when a specific event occurs. It is a very important content in JAVA Web development. Let's learn about the java listener with the editor.

What is a listener in java

1 What is a web listener

Web listeners are special classes in Servlets that can help developers monitor specific events in the web. event.

For example, the creation and destruction of ServletRequest; the creation, destruction and modification of variables, etc. You can also add processing before and after certain actions to achieve monitoring.

2 Common uses of listeners

Web listeners are usually used to do the following:

Count the number of people online and use HttpSessionLisener

to load initialization information: Using ServletContextListener

Count website visits

Implement access monitoring

3 Let’s look at the creation and execution process of a listener

First you need to create A listener that implements a certain interface. For example, if I want to monitor the number of people online, I can create the following listener:

public class MyListener implements HttpSessionListener{
    private int userNumber = 0;
    public void sessionCreated(HttpSessionEvent arg0) {
        userNumber++;
        arg0.getSession().setAttribute("userNumber", userNumber);
    }
    public void sessionDestroyed(HttpSessionEvent arg0) {
        userNumber--;
        arg0.getSession().setAttribute("userNumber", userNumber);
    }
}

Then configure the listener in web.xml and in web-app Add:

 <listener>
      <listener-class>com.test.MyListener</listener-class>
  </listener>

Add the number of visitors in JSP:

<body>    
在线人数:<%=session.getAttribute("userNumber") %>
<br/>
</body>

What is a listener in java


The above is the detailed content of What is a listener in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn