Servlet监听器

监听器可以使你的应用对某些事件作出反应。

    · ServletContextListener:应用上下文生命周期监听器。用于监听Web应用的启动和销毁事件。
    · ServletContextAttributeListener:应用上下文属性事件监听器。用于监听Web应用上下文中的属性改变的事件。
    · ServletRequestListener:请求生命周期监听器。用于监听请求的创建和销毁事件。
    · ServletRequestAttributeListener:请求属性事件监听器。用于监听请求中的属性改变的事件。
    · HttpSessionListener:会话生命周期监听器。用于监听会话的创建和销毁事件。
    · HttpSessionActivationListener:会话激活和钝化事件监听器。用于监听会话的激活和钝化的事件。
    · HttpSessionAttributeListener:会话属性事件监听器。用于监听会话中的属性改变的事件。
    · HttpSessionBindingListener:会话值绑定事件监听器。这是唯一不需要在web.xml中设定的Listener。
1、创建一个监听器实现类,统计网站在线人数
    通过ServletContextListener监听,当Web应用上下文启动时,在ServletContext中添加一个List,用来准备存放在线的用户名;然后,可以通过HttpSessionAttributeListener监听,当用户登录成功,把用户名设置到Session中时,同时将用户名存放到ServletContext中的List列表中;最后通过HttpSessionListener监听,当用户注销会话时,将用户名从应用上下文范围中的List列表中删除。
package com.yyq.listener;
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;
import java.util.LinkedList;
import java.util.List;
/**
 * Created by gao on 16-4-14.
 */
public class OnlineListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
    private ServletContext application = null;
    //往会话中添加属性时回调的方法
    public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
        //取得用户名列表
        List<String> online = (List<String>) this.application.getAttribute("online");
        if ("username".equals(httpSessionBindingEvent.getName())) {
            //将当前用户名添加到列表中
            online.add((String) httpSessionBindingEvent.getValue());
        }
        //将添加后的列表重新设置到application属性中
        this.application.setAttribute("online", online);
    }
    //应用上下文初始化会回调的方法
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        //初始化一个application对象
        this.application = servletContextEvent.getServletContext();
        //设置一个列表属性,用于保存在线用户名
        this.application.setAttribute("online",new LinkedList<String>());
    }
    //会话销毁时会回调的方法
    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        //取得用户名列表
        List<String> online = (List<String>) this.application.getAttribute("online");
        //取得当前用户名
        String username = (String) httpSessionEvent.getSession().getAttribute("username");
        //将此用户名从列表中删除
        online.remove(username);
        //将删除后的列表重新设置到application属性中
        this.application.setAttribute("online", online);
    }
    //以下方法用空实现
    @Override
    public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent) {
    }
    @Override
    public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) {
    }
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
    }
    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }
}

2、创建用户登录的Servlet类

package com.yyq.listener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/**
 * Created by gao on 16-4-14.
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置响应内容类型
        req.setCharacterEncoding("utf-8");
        //获取请求参数中的用户名
        String username = req.getParameter("username");
        //往Session中添加属性
        //会触发HttpSessionAttributeListener中的attributeAdded方法
        if (username != null && !username.equals("")) {
            req.getSession().setAttribute("username", username);
        }
        //从应用上下文中获取在线用户名列表
        List<String> online = (List<String>) getServletContext().getAttribute("online");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<html>");
        out.println("<head><title>用户列表</title></head>");
        out.println("<body>");
        out.println("当前用户是:" + username);
        out.println("<hr/><h3>在线用户列表</h3>>");
        int size = ((online == null) ? 0 : online.size());
        for (int i = 0; i < size; i++) {
            if (i > 0) {
                out.println("<br />");
            }
            out.println(i + 1 + "." + online.get(i));
        }
        //注意:要对连接URL进行自动重写处理
        out.println("<hr/><a href="" + resp.encodeURL("logout") + "">注销</a>");
        out.println("</body>");
        out.println("</html>");
        out.flush();
        out.close();
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    @Override
    public void destroy() {
        //
    }
    @Override
    public void init() throws ServletException {
        //
    }
}
 
3、创建用户注销的Servlet类
package com.yyq.listener;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
/**
 * Created by gao on 16-4-14.
 */
public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       //设置响应内容类型
        req.setCharacterEncoding("utf-8");
        //销毁会话,会触发SessionLinstener中的sessionDestroyed方法
        req.getSession().invalidate();
        //从应用上下文中获取在线用户名列表
        List<String> online = (List<String>)getServletContext().getAttribute("online");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<html>");
        out.println("<head><title>用户列表</title></head>");
        out.println("<body>");
        out.print("<h3>在线用户列表</h3>");
        int size = ((online == null) ? 0 : online.size());
        for (int i = 0; i < size; i++) {
            if (i > 0) {
                out.println("<br />");
            }
            out.println(i + 1 + "." + online.get(i));
        }
        out.println("<hr><a href="index.jsp">主页</hr>");
        out.println("</body>");
        out.println("</html>");
        out.flush();
        out.close();
    }
    @Override
    public void destroy() {
        //
    }
    @Override
    public void init() throws ServletException {
       //
    }
}

4、web.xml配置监听器、LoginServlet和LogoutServlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
           version="3.0">
  <!--注册一个监听器-->
    <listener>
        <!--指定监听器实现类的全限定名-->
        <listener-class>com.yyq.listener.OnlineListener</listener-class>
    </listener>
    <!--配置LoginServlet-->
    <servlet>
        <servlet-name>loginservlet</servlet-name>
        <servlet-class>com.yyq.listener.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>loginservlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
    <!--配置LogoutServlet-->
    <servlet>
        <servlet-name>logoutservlet</servlet-name>
        <servlet-class>com.yyq.listener.LogoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>logoutservlet</servlet-name>
        <url-pattern>/logout</url-pattern>
    </servlet-mapping>
</web-app>

5、登录页面index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title></title>
</head>
<body>
<form action="login" method="post">
    用户名:<input type="text" name="username">
    <input type="submit" value="登录">
    <br />
    <br />
</form>
</body>
</html>

6、启动Tomcat,输入:http://localhost:8080/index.jsp

 
输入yangyuqin,点击登录:
 
 
点击注销链接:
 
 
 
 
原文地址:https://www.cnblogs.com/yangyquin/p/5427260.html