Java Web 基础 - 监听器

2018-10-10  本文已影响15人  千反田爱瑠爱好者

根据监听的事件划分监听器

<context-param>
    <param-name>initParam</param-name>
    <param-value>ywh</param-value>
</context-param>
<listener>
    <listener-class>com.ywh.listener.MyServletContextListener </listener-class>
</listener>
<listener>
    <listener-class>com.ywh.listener.MyHttpSessionListener</listener-class>
</listener>
<listener>
    <listener-class>com.ywh.listener.MyServletRequestListener</listener-class>
</listener>
<listener>
    <listener-class>com.ywh.listener.MyServletContextAttributeListener</listener-class>
</listener>
<listener>
    <listener-class>com.ywh.listener.MyHttpSessionAttributeListener</listener-class>
</listener>
<listener>
    <listener-class>com.ywh.listener.MyServletRequestAttributeListener</listener-class>
</listener>
<session-config>
    <session-timeout>1</session-timeout>
</session-config>

监听域对象自身的创建销毁事件监听器

ServletContextListener

监听 ServletContext,可作为定时器或全局属性对象加载(缓存、数据库)。

MyServletContextListener .java

public class MyServletContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent servletcontextevent) {
        String initParam = servletcontextevent.getServletContext().getInitParameter("initParam");
        System.out.println("context initialized : initParam = " + initParam);
    }

    public void contextDestroyed(ServletContextEvent servletcontextevent) {
        System.out.println("context destroyed");
    }
}

HttpSessionListener

监听 HttpSession ,在一个 Web 应用中可以有多个 HttpSession 对象、一个 HttpSession 可注册多个 Listener,常用于统计在线人数、记录访问日志。

MyHttpSessionListener.java

public class MyHttpSessionListener implements HttpSessionListener {

    public void sessionCreated(HttpSessionEvent HttpSessionevent) {
        System.out.println("session created");
    }

    public void sessionDestroyed(HttpSessionEvent HttpSessionevent) {
        System.out.println("session destroyed");
    }
}

ServletRequestListener

监听 ServletRequest 对象,一个 ServletRequest 可注册多个 Listener,可用于读取参数、记录访问历史。

MyServletRequestListener.java

public class MyServletRequestListener implements ServletRequestListener {

    public void requestDestroyed(ServletRequestEvent servletrequestevent) {
        System.out.println("requestDestroyed ");
    }

    public void requestInitialized(ServletRequestEvent servletrequestevent) {
        String name = servletrequestevent.getServletRequest().getParameter("name");    // 获取 URL 中的参数 name
        System.out.println("requestInitialized name:" + name);
    }
}

监听域对象中的属性增加和删除的事件监听器

其中各有三种操作分别为 attributeAdded、attributeRemoved、attributeReplaced。

ServletContextAttributeListener

以创建为例,销毁同理。

init.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
    request.setAttribute("requestName", "requestValue");
    request.getSession().setAttribute("sessionName", "sessionValue");
    request.getSession().getServletContext().setAttribute("contextName", "contextValue");
    request.setAttribute("requestName", "requestValue");
    request.removeAttribute("requestName");
%>
...

<body>
    <button onclick="location.href='<%=request.getContextPath()%>/init.jsp';">Init</button>
    <button onclick="location.href='<%=request.getContextPath()%>/destory.jsp';">Destory</button>
</body>

ServletContextAttributeListener.java

public class MyServletContextAttributeListener implements ServletContextAttributeListener {

    public void attributeAdded(ServletContextAttributeEvent servletcontextattributeevent) {
        System.out.println("ServletContext_attributeAdded:" + servletcontextattributeevent.getName());
    }

    public void attributeRemoved(ServletContextAttributeEvent servletcontextattributeevent) {
        System.out.println("ServletContext_attributeRemoved:" + servletcontextattributeevent.getName());
    }

    public void attributeReplaced(ServletContextAttributeEvent servletcontextattributeevent) {
        System.out.println("ServletContext_attributeReplaced:" + servletcontextattributeevent.getName());
    }
}

监听绑定到 HttpSession 域中的某个对象的状态的事件监听器

HttpSession 中的对象状态:

对应的 Servlet 的监听器规范:

Session 钝化机制

Session 默认是存放在服务器内存中,服务器把不常用的 Session 对象序列化存储(为 XML 文件)、需要使用时再反序列化到内存中,可以节省内存(由服务器自动完成)。

Tomcat 中的 Session 钝化机制 Tomcat 中的 Session 钝化机制

注意创建的不是监听器,而是普通的 JavaBean(实现接口),状态指的是 Session 的对象状态(而不是监听器状态)。

User.java

public class User implements HttpSessionBindingListener, HttpSessionActivationListener, Serializable {   // 要实现钝化和活化必须实现 Serializable 
    private String username;
    private String password;

    public void valueBound(HttpSessionBindingEvent httpsessionbindingevent) {
        System.out.println("valueBound Name:" + httpsessionbindingevent.getName());
    }

    public void valueUnbound(HttpSessionBindingEvent httpsessionbindingevent) {
        System.out.println("valueUnbound Name:" + httpsessionbindingevent.getName());
    }

    public String getUsername() { return username; }

    public void setUsername(String username) { this.username = username; }

    public String getPassword() { return password; }

    public void setPassword(String password) { this.password = password; }
    
    // 钝化
    public void sessionWillPassivate(HttpSessionEvent httpsessionevent) {
        System.out.println("sessionWillPassivate " + httpsessionevent.getSource());
    }

    // 活化
    public void sessionDidActivate(HttpSessionEvent httpsessionevent) {
        System.out.println("sessionDidActivate " + httpsessionevent.getSource());
    }
}

init.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%
    request.getSession().setAttribute("currentUser", new com.imooc.entity.User());
%>

Servlet 3.0 下监听器的使用

使用 Servlet 3.0 必须满足:

监听器注解
@WebListener("This is My Servlet 3.0 Listener")
public class MyServletContextListener implements ServletContextListener {

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("contextDestroyed");
    }

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println("contextInitialized");
    }
}
上一篇下一篇

猜你喜欢

热点阅读