The author 1:try The abnormality of love
Author 2: Changan Scattered people
the next afternoon more busy (in fact, today are very busy), think about the online number of statistical aspects of the realization, the Internet to find the knowledge of this area, the original idea is that the management session, if the session destroyed on the reduction, if the user has added a new, but if the user illegally quit , such as: not log off, close the browser, etc., the user's session is not managed, and finally decided to use the Httpsessionlistener interface or Httpsessionbindinglistener interface to achieve, Control by monitoring the new and destroyed session, as detailed below.
First add the landing page index.jsp
<% @ page contentType = "text / html; charset = utf-8"%>
<html>
<head>
<title> test </ title>
</ head>
<body>
<form action = "login.jsp" method = "post">
Username: <input type = "text" name = "username" />
<br />
<input type = "submit" value = "login" />
</ form>
</ body>
</ html>
Click on login.jsp after login (for convenience, use jsp as a servlet, remember to change it when students use it)
<% @ page contentType = "text / html; charset = utf-8"%>
<% @ page import = "java.util. *"%>
<%
request.setCharacterEncoding ("UTF-8");
// Get login username
String username = request.getParameter ("username");
// save username in session
session.setAttribute ("username", username);
// put username in online list
List onlineUserList = (List) application.getAttribute ("onlineUserList");
// need to initialize before first use
if (onlineUserList == null) {
onlineUserList = new ArrayList ();
application.setAttribute ("onlineUserList", onlineUserList);
}
onlineUserList.add (username);
// success
response.sendRedirect ("result.jsp");
%>
Login successfully jump to display page result.jsp
<% @ page contentType = "text / html; charset = utf-8"%>
<% @ page isELIgnored = "false"%>
<% @ page import = "java.util.List"%>
<h3> Hi: $ {username} [<a href="logout.jsp"> Logout </a>] </ h3>
Current users:
<table>
<%
List onlineUserList = (List) application.getAttribute ("onlineUserList");
for (int i = 0; i <onlineUserList.size (); i ++) {
String onlineUsername = (String) onlineUserList.get (i);
%>
<tr>
<td> <% = onlineUsername%> </ td>
</ tr>
<%
}
%>
</ table>
Click on logout.jsp page
<% @ page contentType = "text / html; charset = utf-8"%>
<% @ page import = "java.util. *"%>
<%
// Get login username
String username = (String) session.getAttribute ("username");
// destroy session
session.invalidate ();
// remove username from online list
List onlineUserList = (List) application.getAttribute ("onlineUserList");
onlineUserList.remove (username);
// success
response.sendRedirect ("index.jsp");
%>
OK, there are login, view, logout pages, let's start to create a new listener
1.HttpSessionListener
Add class OnlineUserListener and inherit HttpSessionListener. There are two methods in HttpSessionListener: sessionCreated (HttpSessionEvent event) and sessionDestroyed (HttpSessionEvent event). The former is to listen for new session and the latter is to listen for session destruction.
OnlineUserListener code is as follows:
package com.test;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/ **
* @author version
* /
public class OnlineUserListener implements HttpSessionListener {
public void sessionCreated (HttpSessionEvent event) {
System.out.println ("New session:" + event.getSession (). GetId ());
}
public void sessionDestroyed (HttpSessionEvent event) {
HttpSession session = event.getSession ();
ServletContext application = session.getServletContext ();
// Get login username
String username = (String) session.getAttribute ("username");
// remove username from online list
List onlineUserList = (List) application.getAttribute ("onlineUserList");
onlineUserList.remove (username);
System.out.println (username + "Exited!");
}
}
web.xml configuration:
<listener>
<listener-class> com.test.OnlineUserListener </ listener-class>
</ listener>
Once the listener finds that the sessionDestoryed method is called, it deletes its user from the number of online users. In the following two cases, the sessionDestoryed event occurs
a. When executing the session.invalidate () method
session.invalidate () method is called in logout.jsp
b.session session timeout
The default timeout event for a session is 30 minutes, and the session is automatically destroyed after 30 minutes
HttpSessionBindingListener
Although HttpSessionBindingListener is called a listener, its usage is completely different from HttpSessionListener. Let's actually see how it is used.
Create a new class OnlineUserBindingListener, implement the HttpSessionBindingListener interface, and pass the username parameter in the constructor. There are two methods in the HttpSessionBindingListener: valueBound (HttpSessionBindingEvent event) and valueUnbound (HttpSessionBindingEvent event).
The so-called session data binding is to call session.setAttribute () to save HttpSessionBindingListener into the session.
Do this step in login.jsp:
<% @ page import = "com.test.OnlineUserBindingListener"%>
<% @ page contentType = "text / html; charset = utf-8"%>
<% @ page import = "java.util. *"%>
<%
request.setCharacterEncoding ("UTF-8");
// Get login username
String username = request.getParameter ("username");
// put username in online list
session.setAttribute ("onlineUserBindingListener", new OnlineUserBindingListener (username));
// success
response.sendRedirect ("result.jsp");
%>
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 before it can listen.
From the scope of monitoring, HttpSessionListener can be set once to monitor all sessions. HttpSessionBindingListener is usually one-to-one.
It is this difference that makes the advantages of HttpSessionBindingListener. We can make each listener correspond to a username. This eliminates the need to read the username in the session each time. Further, all the code that operates the online list can be moved into the listener. maintain.
The HttpSessionBindingListener code is as follows:
package com.test;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
public class OnlineUserBindingListener implements HttpSessionBindingListener {
String username;
Hell
public OnlineUserBindingListener (String username) {
this.username = username;
}
public void valueBound (HttpSessionBindingEvent event) {
HttpSession session = event.getSession ();
ServletContext application = session.getServletContext ();
// put username in online list
List onlineUserList = (List) application.getAttribute ("onlineUserList");
// need to initialize before first use
if (onlineUserList == null) {
onlineUserList = new ArrayList ();
application.setAttribute ("onlineUserList", onlineUserList);
}
onlineUserList.add (this.username);
}
public void valueUnbound (HttpSessionBindingEvent event) {
HttpSession session = event.getSession ();
ServletContext application = session.getServletContext ();
// remove username from online list
List onlineUserList = (List) application.getAttribute ("onlineUserList");
onlineUserList.remove (this.username);
System.out.println (this.username + "Exit.");
}
}
Here you can directly use the username of the listener to operate the online list, and you no longer have to worry about whether a username exists in the session.
The triggering conditions of valueUnbound are the following three cases:
a. When session.invalidate () is executed.
b.session timeout, when automatically destroyed.
c. execute session.setAttribute ("onlineUserListener", "other objects"); or session.removeAttribute ("onlineUserListener"); when the listener is deleted from the session.
Therefore, as long as the listener is not deleted from the session, you can listen to the destruction of the session.
Note: Three ways to set session timeout (invalidation) in Java
1. Set in the web container (here tomcat as an example)
Set in tomcat-5.0.28 \ conf \ web.xml, the following is the default configuration in tomcat 5.0:
<!-===================== Default Session Configuration ==================->
<!-You can set the default session timeout (in minutes) for all newly->
<!-created sessions by modifying the value below.->
<session-config>
<session-timeout> 30 </ session-timeout>
</ session-config>
Tomcat defaults the session timeout time to 30 minutes, which can be modified as required. Negative numbers or 0 are unlimited session expiration times.
2. Set in the project's web.xml
<!-Time unit is minute->
<session-config>
<session-timeout> 15 </ session-timeout>
</ session-config>
3. Set by Java code
session.setMaxInactiveInterval (30 * 60); // in seconds
Three ways of priority: 1 <2 <3
Using HttpSessionListener and HttpSessionBindingListener to achieve online statistics