In the afternoon, I was relatively idle (in fact, today I was very idle). I thought about the implementation of online user statistics and found some knowledge on the Internet. My first thought was to manage sessions, if the session is destroyed, it will be reduced. If a new user is logged in, but the user unexpectedly exits, for example, the user does not log out or close the browser. This user's session cannot be managed, finally, we decided to use the HttpSessionListener interface or the HttpSessionBindingListener interface to implement the control by monitoring the creation and destruction of the session, as detailed below.
Add index. jsp
01
<% @ Page contentType = "text/html; charset = UTF-8" %>
02
<Html>
03
<Head>
04
<Title> test </title>
05
</Head>
06
<Body>
07
<Form action = "login. jsp" method = "post">
08
Username: <input type = "text" name = "username"/>
09
<Br/>
10
<Input type = "submit" value = "login"/>
11
</Form>
12
</Body>
13
</Html>
Click the login. jsp to jump to after login (for convenience, use jsp as the servlet and remember to change it when the students use it)
01
<% @ Page contentType = "text/html; charset = UTF-8" %>
02
<% @ Page import = "java. util. *" %>
03
<%
04
Request. setCharacterEncoding ("UTF-8 ");
05
// Obtain the logon Username
06
String username = request. getParameter ("username ");
07
// Save the user name to the session
08
Session. setAttribute ("username", username );
09
// Put the user name in the online list
10
List onlineUserList = (List) application. getAttribute ("onlineUserList ");
11
// Initialization is required before use for the first time.
12
If (onlineUserList = null ){
13
OnlineUserList = new ArrayList ();
14
Application. setAttribute ("onlineUserList", onlineUserList );
15
}
16
OnlineUserList. add (username );
17
// Succeeded
18
Response. sendRedirect ("result. jsp ");
19
%>
Log on to the displayed page. result. jsp
1
<% @ Page contentType = "text/html; charset = UTF-8" %>
2
<% @ Page isELIgnored = "false" %>
3
<% @ Page import = "java. util. List" %>
01
<H3> hello, $ {username} [<a href = "logout. jsp"> logout </a>] 02
Current online user:
03
<Table>
04
<%
05
List onlineUserList = (List) application. getAttribute ("onlineUserList ");
06
For (int I = 0; I <onlineUserList. size (); I ++ ){
07
String onlineUsername = (String) onlineUserList. get (I );
08
%>
09
<Tr>
10
<Td> <% = onlineUsername %> </td>
11
</Tr>
12
<%
13
}
14
%>
15
</Table>
Click Log out. jsp on the logout page.
01
<% @ Page contentType = "text/html; charset = UTF-8" %>
02
<% @ Page import = "java. util. *" %>
03
<%
04
// Obtain the logon Username
05
String username = (String) session. getAttribute ("username ");
06
// Destroy the session
07
Session. invalidate ();
08
// Delete the user name from the online list
09
List onlineUserList = (List) application. getAttribute ("onlineUserList ");
10
OnlineUserList. remove (username );
11
// Succeeded
12
Response. sendRedirect ("index. jsp ");
13
%>
OK. The login, view, and logout pages are all available. Next, create a listener.
1. HttpSessionListener
The OnlineUserListener class is added to inherit from HttpSessionListener. HttpSessionListener has two methods: sessionCreated (HttpSessionEvent event) and sessionDestroyed.
The OnlineUserListener code is as follows:
01
Package com. test;
02
03
Import java. util. List;
04
Import javax. servlet. ServletContext;
05
Import javax. servlet. http. HttpSession;
06
Import javax. servlet. http. HttpSessionEvent;
07
Import javax. servlet. http. HttpSessionListener;
08
/**
09
* @ Author version
10
*/
11
Public class OnlineUserListener implements HttpSessionListener {
12
13
Public void sessionCreated (HttpSessionEvent event ){
14
System. out. println ("new session:" + event. getSession (). getId ());
15
}
16
Public void sessionDestroyed (HttpSessionEvent event ){
17
HttpSession session = event. getSession ();
18
ServletContext application = session. getServletContext ();
19
// Obtain the logon Username
20
String username = (String) session. getAttribute ("username ");
21
// Delete the user name from the online list
22
List onlineUserList = (List) application. getAttribute ("onlineUserList ");
23
OnlineUserList. remove (username );
24
System. out. println (username + "has exited! ");
25
}
26
}
Web. xml configuration:
1
<Listener>
2
<Listener-class> com. test. OnlineUserListener </listener-class>
3
</Listener>
Once the listener finds that the sessionDestoryed method is called, it will delete its users from the number of online users. In the following two cases, the sessionDestoryed event will occur.
A. When the session. invalidate () method is executed
The session. invalidate () method is called in logout. jsp.
B. session Timeout
The default timeout event of a session is 30 minutes, and the session is automatically destroyed 30 minutes later.
2. HttpSessionBindingListener
Although HttpSessionBindingListener is called a listener, its usage is completely different from that of HttpSessionListener. Let's take a look at how it is used.
Create a new class listener to implement the HttpSessionBindingListener interface. The construction method is used to input the username parameter. There are two methods in HttpSessionBindingListener: valueBound (HttpSessionBindingEvent event) and valueUnbound (HttpSessionBindingEvent, the latter is unbinding
To bind session data, call session. setAttribute () to save HttpSessionBindingListener to the session.
Perform this step in login. jsp:
01
<% @ Page import = "com. test. OnlineUserBindingListener" %>
02
<% @ Page contentType = "text/html; charset = UTF-8" %>
03
<% @ Page import = "java. util. *" %>
04
<%
05
Request. setCharacterEncoding ("UTF-8 ");
06
// Obtain the logon Username
07
String username = request. getParameter ("username ");
08
// Put the user name in the online list
09
Session. setAttribute ("onlineUserBindingListener", new OnlineUserBindingListener (username ));
10
// Succeeded
11
Response. sendRedirect ("result. jsp ");
12
%>
This is the biggest difference between HttpSessionBindingListener and HttpSessionListener: HttpSessionListener only needs to be set to web. xml to listen to all sessions in the entire application. HttpSessionBindingListener must be instantiated and put into a session for listening.
Compared to the listening range, HttpSessionListener can listen to all sessions once. HttpSessionBindingListener is usually one-to-one.
This difference makes HttpSessionBindingListener advantageous. We can make each listener correspond to a username, so that we do not need to read username in the session every time, the Code of all online list operations can be moved to listener, which is easier to maintain.
The HttpSessionBindingListener code is as follows:
01
Package com. test;
02
03
Import java. util. ArrayList;
04
Import java. util. List;
05
Import javax. servlet. ServletContext;
06
Import javax. servlet. http. HttpSession;
07
Import javax. servlet. http. HttpSessionBindingEvent;
08
Import javax. servlet. http. HttpSessionBindingListener;
09
10
Public class OnlineUserBindingListener implements HttpSessionBindingListener {
11
String username;
12
13
Public OnlineUserBindingListener (String username ){
14
This. username = username;
15
}
16
Public void valueBound (HttpSessionBindingEvent event ){
17
HttpSession session = event. getSession ();
18
ServletContext application = session. getServletContext ();
19
// Put the user name in the online list
20
List onlineUserList = (List) application. getAttribute ("onlineUserList ");
21
// Initialization is required before use for the first time.
22
If (onlineUserList = null ){
23
OnlineUserList = new ArrayList ();
24
Application. setAttribute ("onlineUserList", onlineUserList );
25
}
26
OnlineUserList. add (this. username );
27
}
28
29
Public void valueUnbound (HttpSessionBindingEvent event ){
30
HttpSession session = event. getSession ();
31
ServletContext application = session. getServletContext ();
32
33
// Delete the user name from the online list
34
List onlineUserList = (List) application. getAttribute ("onlineUserList ");
35
OnlineUserList. remove (this. username );
36
System. out. println (this. username + "exit. ");
37
38
}
39
40
}
Here, you can directly use the username of listener to operate the online list without worrying about the existence of username in the session.
The trigger conditions of valueUnbound are as follows:
A. When session. invalidate () is executed.
B. The session times out and is automatically destroyed.
C. Run session. setAttribute ("onlineUserListener", "other objects"); or session. removeAttribute ("onlineUserListener") to delete the listener from the session.
Therefore, as long as the listener is not deleted from the session, the session can be destroyed.
Author "ybhanxiao"