创建项目:
选择web application,点击next
自定义项目名称
导包操作:
选择file中的project Structure
选择Modules中的Deoendencies中右边的加号
选择第一项
添加tomcat的lib目录下的servlet-api.jar,jsp-api.jar
勾上添加的Jar包,点击apply
添加tomcat,选择add configuration
点击+号,选择tomcat,local
配置tomcat服务器
点击右下角的fix,修改application context
创建src目录下的listense文件,创建ListenseTest.java
添加如下代码:
public class ListenseTest implements HttpSessionListener, ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent){
//获取application
ServletContext servletContext = servletContextEvent.getServletContext();
//设置网站的初始在线人数
servletContext.setAttribute("count",0);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent){
System.out.println("执行contextDestroyed");
}
@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent){
//获取application对象
ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
int count = (int) servletContext.getAttribute("count");
count++;
servletContext.setAttribute("count",count);
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent){
//获取application对象
ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
int count = (int) servletContext.getAttribute("count");
count--;
servletContext.setAttribute("count",count);
}
}
jsp页面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
在线的人数为:${applicationScope.count}
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<listener>
<listener-class>com.ctb.listense.ListenseTest</listener-class>
</listener>
</web-app>
实现效果:
当只用谷歌浏览器打开时
把另外一个浏览器同时打开时