Java listener (Listener)

Listener listens for certain objects to create Web applications, destroy, add, modify, or delete actions occur, and then respond appropriately treated. When the state of an object of listening range changes, the server automatically listener object method invocation. Common Online, initialization information, traffic statistics site statistics and so on when the system is loaded on the site.

classification:

1. Press listening objects into

It can be divided:

  • ServletContext object listener
  • HttpSession object listener
  • ServletRequest object listener

2. monitor events division

It can be divided:

  • Object creation and destruction of their listeners
  • Property creation and the elimination of listener objects
  • The state of an object changes in the session listener
     

web.xml to configure the Listener

<listener>
  <listener-class>com.csdn.test.o</listener-class>
</listener>

Note: listeners> Filters> servlet, allocation of time to pay attention to the order

If you are using Servlet3.0 above, the listener configuration can be done in code through direct annotation, no longer need to configure in web.xml. as follows:

@WebListener   //在此注明以下类是监听器
public class onLineCount implements HttpSessionListener {

    public int count=0;
    public void sessionCreated(HttpSessionEvent arg0) {
        count++;
        arg0.getSession().getServletContext().setAttribute("Count", count);

    }

    @Override
    public void sessionDestroyed(HttpSessionEvent arg0) {
        count--;
        arg0.getSession().getServletContext().setAttribute("Count", count);
    }

Attachment: the servlet listener in the API

 

Guess you like

Origin blog.csdn.net/qq_42239765/article/details/90546909