Java implements the online user monitoring function based on servlet listeners, servlet listeners

Source: Internet
Author: User

Java implements the online user monitoring function based on servlet listeners, servlet listeners

This example describes how to monitor the number of online users in Java based on servlet listeners. We will share this with you for your reference. The details are as follows:

1. Analysis:

The number of online users of a website can be monitored through ServletContextListener. When the Web application context is started, add a List to ServletContext. the user name is used to store the online user name, and then listens through HttpSessionAttributeListener. When the user logs on successfully, set the user name to the Session. At the same time, the user name method is added to the List of ServletContext, and then listened through HttpSessionListener. When the user logs out of the session, the user name is deleted from the List in the context of the application.

2. Notes

During the test, you must start different browsers to log on to different users. You can only click the Logout button to reduce the number of online users. Closing the browser cannot reduce the number of online users.

3. Project source code

(1) java code

OnlineListener class

Package com. smalle. listener; import java. util. using list; import java. util. list; import javax. servlet. servletContext; import javax. servlet. servletContextEvent; import javax. servlet. servletContextListener; import javax. servlet. http. httpSessionAttributeListener; import javax. servlet. http. httpSessionBindingEvent; import javax. servlet. http. httpSessionEvent; import javax. servlet. http. httpSessionListener; public class OnlineListener implements ServletContextListener, listener, HttpSessionListener {private ServletContext application = null; // method called back when the application context starts @ Override public void contextInitialized (ServletContextEvent e) {// Initialize an application object application = e. getServletContext (); // sets a list attribute to save the online user name this. application. setAttribute ("online", new parameter list <String> ();} // callback Method for adding an attribute to a session @ Override public void attributeAdded (HttpSessionBindingEvent e) {// obtain the username List <String> onlines = (List <String>) this. application. getAttribute ("online"); if ("username ". equals (e. getName () {onlines. add (String) e. getValue ();} // reset the added list to the application attribute column. this. application. setAttribute ("online", onlines);} // method called back when the session is destroyed @ Override public void sessionDestroyed (HttpSessionEvent e) {// obtain the username List <String> onlines = (List <String>) this. application. getAttribute ("online"); // get the current username String username = (String) e. getSession (). getAttribute ("username"); // Delete this user from the list. remove (username); // You can reset the deleted list to the application attribute. this. application. setAttribute ("online", onlines);} public void sessionCreated (HttpSessionEvent e) {} public void attributeRemoved (HttpSessionBindingEvent e) {} public void attributeReplaced (HttpSessionBindingEvent e) {} public void contextDestroyed (ServletContextEvent e ){}}

LoginServlet class

Package com. smalle. listener; import java. io. IOException; import java. io. printWriter; import java. util. list; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class LoginServlet extends HttpServlet {private static final long serialVersionUID = 1L; public void doGet (HttpServletRequ Est request, HttpServletResponse response) throws ServletException, IOException {this. doPost (request, response);} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); // set the response content type String username = request. getParameter ("username"); // get the username in the Request Parameter // Add attributes to the session, triggering attr in HttpSessionAttributeListener IbuteAdded method if (username! = Null &&! Username. equals ("") {request. getSession (). setAttribute ("username", username);} // obtain the online username List from the application context <String> online = (List <String>) getServletContext (). getAttribute ("online"); System. out. println ("LoginServlet" + online); response. setContentType ("text/html; charset = UTF-8"); PrintWriter out = response. getWriter (); out. println (""); out. println ("<title> User List </title>"); out. println (""); out. println (" Current User: "+ username); out. print (" 

LogoutServlet class

Package com. smalle. listener; import java. io. IOException; import java. io. printWriter; import java. util. list; import javax. servlet. servletException; import javax. servlet. http. httpServlet; import javax. servlet. http. httpServletRequest; import javax. servlet. http. httpServletResponse; public class LogoutServlet extends HttpServlet {public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this. doPost (request, response);} public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request. setCharacterEncoding ("UTF-8"); // sets the response content type // destroys the session and triggers the sessionDestroyed Method request in SessionLinstener. getSession (). invalidate (); // obtain the online user name List from the application context <String> online = (List <String>) getServletContext (). getAttribu Te ("online"); response. setContentType ("text/html; charset = UTF-8"); PrintWriter out = response. getWriter (); out. println (""); out. println ("<title> User List </title>"); out. println (""); out. print ("

(2) web. xml Code

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>testServlet</display-name>  <listener>    <listener-class>com.smalle.listener.OnlineListener</listener-class>  </listener>  <servlet>    <servlet-name>LoginServlet</servlet-name>    <servlet-class>com.smalle.listener.LoginServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>LoginServlet</servlet-name>    <url-pattern>/loginListener</url-pattern>  </servlet-mapping>  <servlet>    <servlet-name>LogoutServlet</servlet-name>    <servlet-class>com.smalle.listener.LogoutServlet</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>LogoutServlet</servlet-name>    <url-pattern>/logoutListener</url-pattern>  </servlet-mapping> <welcome-file-list>  <welcome-file>index.jsp</welcome-file> </welcome-file-list></web-app>

(3) Presentation Layer Code

<! DOCTYPE html> 

Related Article

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.