session的使用

一、实现效果
session的使用_第1张图片

session的使用_第2张图片

 

二、实现过程
session的使用_第3张图片

 

三、实验代码

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

"-//W3C//DTD HTML 4.01 Transitional//EN">

  
    <base href="<%=basePath%>">
    
    My JSP <span style="color: #800000;">'</span><span style="color: #800000;">index.jsp</span><span style="color: #800000;">'</span> starting page
    "pragma" content="no-cache">
    "cache-control" content="no-cache">
    "expires" content="0">    
    "keywords" content="keyword1,keyword2,keyword3">
    "description" content="This is my page">
    
  
  
  当前在线人数:
  
  <%=(Integer)application.getAttribute("Online")%>
  


index.jsp



package com.a;

import javax.servlet.ServletContextAttributeEvent;
import javax.servlet.ServletContextAttributeListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestAttributeEvent;
import javax.servlet.ServletRequestAttributeListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionActivationListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * Application Lifecycle Listener implementation class logNum
 *
 */
@WebListener
public class logNum implements HttpSessionListener {
    private int online=0;

    public void sessionCreated(HttpSessionEvent arg0)  { 
        online++;
        arg0.getSession().getServletContext().setAttribute("Online",new Integer(online));
    }
    
    public void sessionDestroyed(HttpSessionEvent arg0)  { 
        online--;
        arg0.getSession().getServletContext().setAttribute("Online",new Integer(online));
   }
}

logNum.java(监听器)


"1.0" encoding="UTF-8"?>
"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">
  Session
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
    
        class>com.a.logNumclass>
    
    
        1
    


web.xml

四、网盘链接
链接: https://pan.baidu.com/s/1p6LL4IGWN83Ee2fFVxXOHQ 提取码: g8ak 复制这段内容后打开百度网盘手机App,操作更方便哦

你可能感兴趣的:(session的使用)