Home > Java > Java Tutorial > body text

What is a listener in java

little bottle
Release: 2019-05-25 16:29:06
Original
4743 people have browsed it

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);
    }
}
Copy after login

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

 
      com.test.MyListener
  
Copy after login

Add the number of visitors in JSP:

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

Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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 [email protected]
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!