案例:监听域对象的生命周期

任务目标

实现监听ServletContext HttpSession ServletRequest这三个域对象的生命周期

创建监听器MyListener

@WebListener
public class MyListener implements
        ServletContextListener, HttpSessionListener,ServletRequestListener {
    public void contextInitialized(ServletContextEvent arg0) {
        System.out.println(" the web application initialization process is starting.");
    }
    public void contextDestroyed(ServletContextEvent arg0) {
        System.out.println("a ServletContext is about to be shut down.");
    }
    public void requestInitialized(ServletRequestEvent arg0) {
        System.out.println("a ServletRequest is about to come into scope of the web application.");
    }
    public void requestDestroyed(ServletRequestEvent arg0) {
        System.out.println("a ServletRequest is about to go out of scope of the web application.");
    }
    public void sessionCreated(HttpSessionEvent arg0) {
        System.out.println("a session has been created.");
    }
    public void sessionDestroyed(HttpSessionEvent arg0) {
        System.out.println("a session is about to be invalidated.");
    }
}

启动项目,控制台查看“正在启动ServletContext对象初始化”

06-Nov-2023 13:56:28.123 信息 [main] org.apache.catalina.startup.Catalina.start Server startup in [113] milliseconds
Connected to server
[2023-11-06 01:56:28,510] Artifact javaweb-demo:war exploded: Artifact is being deployed, please wait...
06-Nov-2023 13:56:29.924 信息 [RMI TCP Connection(3)-127.0.0.1] org.apache.jasper.servlet.TldScanner.scanJars 至少有一个JAR被扫描用于TLD但尚未包含TLD。 为此记录器启用调试日志记录,以获取已扫描但未在其中找到TLD的完整JAR列表。 在扫描期间跳过不需要的JAR可以缩短启动时间和JSP编译时间。
 the web application initialization process is starting.
06-Nov-2023 13:56:30.514 警告 [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.util.SessionIdGeneratorBase.createSecureRandom Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [467] milliseconds.

关闭项目,查看ServletContext对象即将被销毁

06-Nov-2023 13:57:59.054 信息 [main] org.apache.catalina.core.StandardServer.await A valid shutdown command was received via the shutdown port. Stopping the Server instance.
06-Nov-2023 13:57:59.055 信息 [main] org.apache.coyote.AbstractProtocol.pause Pausing ProtocolHandler ["http-nio-80"]
06-Nov-2023 13:57:59.150 信息 [main] org.apache.catalina.core.StandardService.stopInternal 正在停止服务[Catalina]
a ServletContext is about to be shut down.
06-Nov-2023 13:57:59.192 信息 [main] org.apache.coyote.AbstractProtocol.stop 正在停止ProtocolHandler ["http-nio-80"]
06-Nov-2023 13:57:59.204 信息 [main] org.apache.coyote.AbstractProtocol.destroy 正在摧毁协议处理器 ["http-nio-80"]
Disconnected from server

创建测试用IndexServlet

测试HttpSessionListener,ServletRequestListener 

@WebServlet(name = "IndexServlet", value = "/IndexServlet")
public class IndexServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 解决乱码问题
        response.setContentType("text/html;charset=utf-8");
        // 创建或者获取保存用户信息的Session对象
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user == null) {
            response.getWriter().print("您还没有登录,请<a href='"+request.getContextPath()+"/login.html'>登录   </a>");
        } else {
            response.getWriter().print("您已登录,欢迎你," + user.getUsername() + "!");
            response.getWriter().print("<a href='"+request.getContextPath()+"/LogoutServlet'>退出</a>");
            // 创建Cookie存放Session的标识号
            Cookie cookie = new Cookie("JSESSIONID", session.getId());
            cookie.setMaxAge(60 * 60 * 24);
            cookie.setPath(request.getContextPath());
            response.addCookie(cookie);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

 设置session超时时间

  <session-config>  
    <session-timeout>2</session-timeout>
  </session-config>

再次启动项目,查看结果

访问测试页面http://localhost:8080/chapter08/IndexServlet

a ServletRequest is about to come into scope of the web application.
a session has been created.
a ServletRequest is about to go out of scope of the web application.

 浏览器关闭或者不刷新,两分钟后Session对象都会被销毁,所以控制台输出以下内容

a ServletRequest is about to come into scope of the web application.
a session has been created.
a ServletRequest is about to go out of scope of the web application.
a session is about to be invalidated.

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值