Servlet listener usage

Source: Internet
Author: User

Due to work requirements, I recently looked for some solutions and found that Listener is a good thing,

Can listen to the session, application's create, destroy, can listen to the session, Application

The changes in property binding can be applied to "online user count Statistics", "data cache", and other aspects,

The following are some documents.

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}

 

 

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

 

 

In terms of scope, Servlet has the following scopes: servletcontext, httpsession, and servletrequest.

Context range:

Servletcontextlistener:
Global monitoring of an application is enabled as the application starts and disappears as the application disappears. There are two main methods:

Contextdestroyed (servletcontextevent event)

Called when the application is closed

Contextinitialized (servletcontextevent event)

Called at application startup

This listener is mainly used for some work to be completed as the application starts, that is, what many people say I want
When starting ..........
Initialize global variables, as shown in figure

Public void contextinitialized (servletcontextevent event ){
Servletcontex SC = event. getservletcontext ();
SC. setattribute (name, value );
}

In the future, you can get servletcontext (). getattribute (name) in any servlet );
I like to use it for daemon, that is, in the contextinitialized (servletcontextevent event)
Implement a timer in the method, and then let the application make the timer work at each startup:
Program code:
Public void contextinitialized (servletcontextevent event ){
Timer = new timer ();
Timer. Schedule (New timertask (){
Public void run (){
// Do any things
}
}, 0, time interval );
}

Some people say that timer can only specify how long it takes to do things or when it takes to do things from now on.
How can I do a job on the first day of every month or at every day?
You only need to set an interval and then judge whether the time period is the same. For example, if you do this on the first day of every month, then you
Set the time interval to a day, that is, a cycle of 24 hours, and then judge the date new date (). getdate () = 1 in the run Method
That's all. If it's every day, set the interval to hour, and then judge new date (). gethour () in run ()
= 12. Just do something again.

Servletcontextattributelistener:

This listener monitors events of servletcontex objects in setattribute () and removeattribute (). Note that
That is, when a "global variable" is added (set for the first time), replace (re-assigned to an existing variable), and remove.
Call the following three methods:
Public void attributeadded (servletcontextattributeevent scab)
Which global variables are added, and you can obtain which context variables are automatically set when the container is started:
Program code:
Public void attributeadded (servletcontextattributeevent scab ){
System. Out. println (scab. getname ());
}
Public void attributeremoved (servletcontextattributeevent scab)

Public void attributereplaced (servletcontextattributeevent scab)

Session range:
Httpsessionlistener:
This listener mainly monitors events that occur when a session object is generated and destroyed. There are two methods for this listener:
Program code:
Public void sessioncreated (httpsessionevent SE)

Public void sessiondestroyed (httpsessionevent SE)

Generally, when a session object is created, it indicates that there is a new client entering. It can be used to roughly count online users.
Number, note that this is not accurate, because this client may be closed immediately, but the sessiondestroyed method will press
The policy takes a long time.

Httpsessionattributelistener:
Like servletcontextattributelistener, It listens to attribut of a session object and is added (a specific
Attribute of the name is set once), replace (the value of the attribute of the existing name is reset), and remove events.
There are three methods.
Program code:
Public void attributeadded (httpsessionbindingevent SE)

Public void attributeremoved (httpsessionbindingevent SE)

Public void attributereplaced (httpsessionbindingevent SE)

The methods of the above listeners are all about what happened in the servlet logic of the listening application logic. Generally.
We only need to complete the logic function, such as session. setattribute ("AAA", "111 ").
Put it in the session so that I can get it later. I don't care when session. setattribute ("AAA", "111 ");
What do I need to do? (of course, sometimes I need to use it), but you should make a proper explanation for the listener below:

Httpsessionbindinglistener:
The above listeners are used as independent listener to control events in the container, while httpsessionbindinglistener
Monitors the status of this object in an object. If the object implementing this interface is added to a session as a value or
Remove in the session, it will know that it has been used as a session object or has been deleted from the session.
Pure Java objects, objects whose lifecycles are longer than sessions, and other objects whose resources need to be released or changed.
For example:
Session. setattribute ("ABC", "1111 ");
Later session. removeattribute ("ABCD"); Because ABCD is a character, after you remove it from the session, it will
It is automatically recycled by the garbage collector. If it is a connection: (for example, you must never add a connection to the session .)
)
Program code:
Session. setattribute ("ABCD", Conn );

Later session. removeattribute ("ABCD"); in this case, the Conn is removed from the session and you cannot get it.
So you can't close it at all. You don't know when to be removed before removing it, and you can't
Close (), the connection object will die. In addition, some objects can be locked when they are added to a session.
You need to unlock it when it is also removed, because you cannot determine when it will be removed () in the program, add is fine, I can lock it first
Add again, but after removing it, you will not be able to find its handle and cannot unlock it. Therefore, these operations can only be implemented in the object itself.
That is, when an object is added or removed, the notification object calls back the corresponding method:
Program code:
Myconn extends connection implements httpsessionbindinglistener {
Public void valuebound (httpsessionbindingevent SE ){
This. initxxx ();
}
Public void valueunbound (httpsessionbindingevent SE ){

This. Close ();
}
}

Session. setattribute ("AAA", new myconn ());
In this case, if session. removeattribute ("AAA") is called, The valueunbound method is triggered and the user is automatically disabled.
The other objects that need to change the State are the same.

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.