JSP--监听器

1 HttpSessionListener 监听Session的产生和销毁
1.1 Session相关知识:全局session:
HttpSession session = ServletActionContext.getRequest().getSession(); //创建 ActionContext.getContext().getSession().put(“msg”, “Hello World from Session!”); //存
session.setAttribute(“softtypeid”, softtypeid); //存
request.getSession()与request.getSession(true):若存在会话则返回该会话,否则新建一个会话。
request.getSession(false):若存在会话则返回该会话,否则返回NULL
1.2 Demo
实现一个Servlet类创建Session来测试:

public class SessionCreateServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        // 若存在获取该session,不存在则创建一个session
        HttpSession session = req.getSession(true);

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();
        String _sval = (String) session.getAttribute("counter");
        int _counter = 1;

        if (_sval != null) {
            _counter = Integer.parseInt(_sval);
            _counter++;
        }

        session.setAttribute("counter", String.valueOf(_counter));

        out.println("<HEAD><TITLE> "
                + "Session Created Successfully .. Look at OC4J Console to see whether the HttpSessionEvent invoked "
                + "</TITLE></HEAD><BODY>");
        out.println("<P>[<A HREF=\"SessionCreateServlet\">Reload</A>]&nbsp;");
        out.println("[<A HREF=\"SessionDestroyServlet\">Destroy Session</A>]");
        out.println("<h2>Session created Successfully</h2>");
        out.println("Look at the OC4J Console to see whether the HttpSessionEvent was invoked");
        out.println("<h3>Session Data:</h3>");
        out.println("New Session: " + session.isNew());
        out.println("<br>Session ID: " + session.getId());
        out.println("<br>Creation Time: " + new Date(session.getCreationTime()));
        out.println("<br>Last Accessed Time: "
                + new Date(session.getLastAccessedTime()));
        out.println("<BR>Number of Accesses: "
                + session.getAttribute("counter"));
    }
}

实现一个Servlet类销毁Session来测试:

public class SessionDestroyServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        // 创建一个Session,
        HttpSession session = req.getSession(true);
        // 销毁当前session
        session.invalidate();

        res.setContentType("text/html");

        PrintWriter out = res.getWriter();

        out.println("<HEAD><TITLE> "
                + "Session Destroyed Successfully .. Look at OC4J Console to see whether the HttpSessionEvent invoked "
                + "</TITLE></HEAD><BODY>");
        out.println("<P>[<A HREF=\"../index.jsp\">Restart</A>]");
        out.println("<h2> Session Destroyed Successfully</h2>");
        out.println("Look at the OC4J Console to see whether the HttpSessionEvent was invoked");
        out.close();
    }
}

定义一个监听器:

public class SessionLifeCycleEventExample implements ServletContextListener,
        HttpSessionListener {
    public SessionLifeCycleEventExample() {
    }

    ServletContext servletContext;

    /** 实现ServletContextListener application开始执行初始化时执行*/
    public void contextInitialized(ServletContextEvent sce) {
        servletContext = sce.getServletContext();
    }

    /** 实现ServletContextListener ServletContext即将关闭时接收通知*/
    public void contextDestroyed(ServletContextEvent sce) {
    }

    /**
     * 实现自HttpSessionListener,当创建Session是执行。参数hes包含Session信息
     */
    public void sessionCreated(HttpSessionEvent hse) {
        log("CREATE", hse);
        System.out.println("...");
    }

    /**
     * 继承自HttpSessionListener,当关闭Session时执行,参数包含Session信息
     */
    public void sessionDestroyed(HttpSessionEvent hse) {

        HttpSession _session = hse.getSession();
        long _start = _session.getCreationTime();
        long _end = _session.getLastAccessedTime();
        String _counter = (String) _session.getAttribute("counter");
        log("DESTROY, Session Duration:" + (_end - _start) + "(ms) Counter:"
                + _counter, hse);
    }

    protected void log(String msg, HttpSessionEvent hse) {
        String _ID = hse.getSession().getId();
        log("SessionID:" + _ID + "    " + msg);
    }

    protected void log(String msg) {
        System.out.println("[" + getClass().getName() + "] " + msg);
    }
}

web.xml配置:
Listener的配置信息必须在Filter和Servlet之前。

<listener>
      <listener-class>SessionLifeCycleEventExample</listener-class> 
   </listener>
   <servlet>
      <servlet-name>sessioncreate</servlet-name> 
      <servlet-class>SessionCreateServlet</servlet-class> 
   </servlet>
   <servlet>
      <servlet-name>sessiondestroy</servlet-name> 
      <servlet-class>SessionDestroyServlet</servlet-class> 
   </servlet>
   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file> 
   </welcome-file-list>

当创建Session和销毁指定的Session时将会执行指定的方法,具体看注释。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值