Use Listener in java web

Source: Internet
Author: User

Listener is a Servlet Listener that can listen to client requests and server operations. Through the listener, some operations can be automatically triggered, such as the number of online users. When an HttpSession is added, the sessionCreated (HttpSessionEvent se) method is used to increase the number of online users by 1. Common listening interfaces include the following:
# ServletContextAttributeListener listens for operations on the attributes of ServletContext, such as adding, deleting, and modifying attributes.

# ServletContextListener listens to ServletContext. When a ServletContext is created, the contextInitialized (ServletContextEvent sce) method is activated. When ServletContext is destroyed, the contextDestroyed (ServletContextEvent sce) method is activated.

# HttpSessionListener listens for HttpSession operations. When a Session is Created, the session Created (HttpSessionEvent se) method is activated. When a Session is destroyed, the sessionDestroyed (HttpSessionEvent se) method is activated.

# HttpSessionAttributeListener listens for Attribute operations in HttpSession. When an attribute is added to a Session, the attributeAdded (HttpSessionBindingEvent se) method is triggered. When an attribute is deleted in the Session, the attributeRemoved (HttpSessionBindingEvent se) method is triggered; when the Session attribute is reset, The attributeReplaced (HttpSessionBindingEvent se) method is triggered.

Next we will develop a specific example where the listener can count the number of online users. When ServletContext is initialized and destroyed, the corresponding information is printed on the server console. When attributes in ServletContext are added, changed, or deleted, the corresponding information is printed on the server console.

To obtain the above functions, the listener must implement the following three interfaces:

# HttpSessionListener

# ServletContextListener

# ServletContextAttributeListener

For more information about the code, see example 14-9.

[Program source code]

1 // ================================= Program Discription ==================== ======
2 // program name: Example 14-9: EncodingFilter. java
3 // program objective: to learn how to use listeners
4 // ============================================== ======================================
5 import javax. servlet. http .*;
6 import javax. servlet .*;
7
8 public class OnLineCountListener implements HttpSessionListener,
ServletContextListener, ServletContextAttributeListener
9 {
10 private int count;
11 private servletcontext context = NULL;
12
13 public onlinecountlistener ()
14 {
15 COUNT = 0;
16 // setcontext ();
17}
18 // triggered when a session is created
19 public void sessioncreated (httpsessionevent SE)
20 {
21 count ++;
22 setcontext (SE );
23
24}
25 // triggered when a session fails
26 Public void sessiondestroyed (httpsessionevent SE)
27 {
28 count --;
29 setcontext (SE );
30}
31 // set the context attribute, which will stimulate the attributereplaced or attributeadded Method
32 public void setcontext (httpsessionevent SE)
33 {
34 se. getsession (). getservletcontext ().
Setattribute ("online", new INTEGER (count ));
35}
36 // triggered when a new attribute is added
37 public void attributeadded (servletcontextattributeevent event ){
38
39 log ("attributeadded ('" + event. getname () + "', '" +
40 event. getvalue () + "')");
41
42}
43
44 // triggered when a new attribute is deleted
45 public void attributeremoved (servletcontextattributeevent event ){
46
47 log ("attributeremoved ('" + event. getname () + "', '" +
48 event. getvalue () + "')");
49
50}
51
52 // triggered when the attribute is replaced
53 public void attributereplaced (servletcontextattributeevent event ){
54
55 log ("attributereplaced ('" + event. getname () + "', '" +
56 event. getvalue () + "')");
57}
58 // triggered when context is deleted
59 public void contextDestroyed (ServletContextEvent event ){
60
61 log ("contextDestroyed ()");
62 this. context = null;
63
64}
65
66 // triggered during context Initialization
67 public void contextInitialized (ServletContextEvent event ){
68
69 this. context = event. getServletContext ();
70 log ("contextInitialized ()");
71
72}
73 private void log (String message ){
74
75 System. out. println ("ContextListener:" + message );
76}
77}

[Program annotation]
In onlinecountlistener, count indicates the number of online users. onlinecountlistener is automatically executed when the web server is started. After onlinecountlistener is constructed, set count to 0. Each time a session is added, onlinecountlistener automatically calls the sessioncreated (httpsessionevent SE) method. Each time a session is destroyed, onlinecountlistener automatically calls the sessiondestroyed (httpsessionevent SE) method. When the sessioncreated (httpsessionevent SE) method is called, it indicates that another customer is requesting, adding 1 to the number of online users (count) and writing count to servletcontext. Servletcontext information is shared by all clients. In this way, each client can read the current number of online users.

To make the listener take effect, you need to configure it in Web. XML as follows:

<Listener>
<Listener-class> onlinecountlistener </listener-class>
</Listener>

Test procedure:

<% @ Page contenttype = "text/html; charset = gb2312" %>

Current online users:

<Font color = Red> <% = getservletcontext (). getattribute ("online") %> </font> <br>

Exit session:

<Form action = "exit. jsp" method = post>
<Input type = submit value = "exit">
</Form>

GetServletContext (). getAttribute ("onLine") obtains the specific value of count. Client call

<% Session. invalidate (); %>

Make the Session invalid, so that the listener will reduce the count by 1.

[Run the program]
Web. make the above configurations in xml, put OnLineCountListener in the WEB-INF/class directory, start the Web server, and enter the following URL in the browser (depending on the specific situation): http: // 127.0.0.1: 8080, ch14, and listener. jsp

The browser will print the current number of online users. The following output is available on the server:

...
ContextListener: contextInitialized ()
ContextListener: attributeReplaced ('org. apache.
Catalina. WELCOME_FILES ',' [Ljava. lang. String; @ 1d98a ')
...
ContextListener: attributeAdded ('online', '1 ')
ContextListener: attributeReplaced ('online', '1 ')
ContextListener: attributeReplaced ('online', '0 ')
ContextListener: attributeReplaced ('online', '1 ')
ContextListener: attributeReplaced ('online', '2 ')

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.