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.
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>
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!