案例

有一天,老板气冲冲的跑到IT部办公室,对IT经理说有人
冒充她的名字在公司网站论坛上发布虚假消息,要IT经理
赶紧做一个页面,她登陆进去能查看所有在线用户,还可
以删除指定用户。
老板很生气,时间很紧迫,经理决定先用Session监听技
术,快速的我做一个页面,让老板消息气再慢慢连接数据
库完善和修改程序。
  1. 监听ServletContext的创建,初始化时创建一个Map(key存放用户名,value存放客户信息)
  2. 当用户登陆与session发生绑定时监听,将绑定的用户信息放到Map中
  3. 用户登录Servlet,处理用户传过来的登陆信息
  4. login.jsp登陆表单
  5. success_login.jsp登陆成功显示在线人员明细与实现删除功能

实现

登陆页面

两个浏览器,分别用不同的用户名登陆

在线用户

可以显示两个用户在线

删除用户

把老板删除后,只剩下一个经理在线了

项目工程

两浏览器,分别用不同的用户名登陆

代码

监听ServletContext的创建

package offlineUser;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.http.HttpSession;

/**
 * 监听ServletContext的创建,初始化时创建一个map
 *
 */
public class MyServletContextListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce)  { 
    	//map的key存放用户名,value存放客户信息
    	Map<String,HttpSession> map=new HashMap<>();
    	ServletContext servletContext=sce.getServletContext();
    	servletContext.setAttribute("map", map);
    }
	
}

监听用户与session发生绑定

package offlineUser;

import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

/**
 * 当用户登陆与session发生绑定时监听
 *
 */
public class User implements HttpSessionBindingListener {
		private String name;
		private int age;
		
		
   
    public String getName() {
			return name;
		}


		public void setName(String name) {
			this.name = name;
		}


		public int getAge() {
			return age;
		}


		public void setAge(int age) {
			this.age = age;
		}

	
    public void valueBound(HttpSessionBindingEvent event)  { 
    	//得到一个ServletContext
    	ServletContext servletContext=event.getSession().getServletContext();
    	//获取ServletContext域中的map
    	Map<String,HttpSession>map=(Map<String, HttpSession>) servletContext.getAttribute("map");
    	map.put(name, event.getSession());
    	servletContext.setAttribute("map", map);
    	
    	
    }

	
}

用户登录Servlet

package offlineUser;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *用户登录
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		//将网页传过来的用户存到user对象里面
		User user=new User();
		user.setName(request.getParameter("name"));
		//将user对象放到session中
		request.getSession().setAttribute("user", user);
		
		response.sendRedirect(request.getContextPath()+"/seccuss_login.jsp");
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

deleteServlet将在线用户踢出

package offlineUser;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 将在线用户踢出
 */
public class deleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//获取要踢出的用户名
		String name=request.getParameter("name");
		///获取ServletContextr
		HttpSession currentSession=request.getSession();
		ServletContext servletContext=currentSession.getServletContext();
		//从ServletContext中获取map
		Map<String,HttpSession> map=(Map<String, HttpSession>) servletContext.getAttribute("map");
		HttpSession session=map.get(name);
		//将session清空并从map中移除
		if(session!=null) {
			session.invalidate();
			map.remove(name);
		}
		response.sendRedirect(request.getContextPath()+"/seccuss_login.jsp");
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

Login.jsp用户登录网页

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/Login" >
Name:<input name="name" type="text"><br>
<input type="submit" value="提交">

</form>
</body>
</html>

Successlogin.jsp管理在线用户网页

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
	<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<table border="0">
		<tr>	
				<td>序号</td>
				<td>用户名</td>
				<td>操作</td>	
		</tr>
<c:forEach items="${map }" var="a" varStatus="obj">
 		<tr>	
				<td>${obj.count }</td>
				<td>${a.key }</td>
				<td><a href="${pageContext.request.contextPath }/deleteuser?name=${a.key }">删除</a></td>	
		</tr>
</c:forEach>

</table>

</body>
</html>

web.xml

	<?xml version="1.0" encoding="UTF-8"?>
	<web-app xmlns:xsi="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_2_5.xsd" id="WebApp_ID" version="2.5">
	  <display-name>offlineUser</display-name>
	  <welcome-file-list>
	    <welcome-file>index.html</welcome-file>
	    <welcome-file>index.htm</welcome-file>
	    <welcome-file>index.jsp</welcome-file>
	    <welcome-file>default.html</welcome-file>
	    <welcome-file>default.htm</welcome-file>
	    <welcome-file>default.jsp</welcome-file>
	  </welcome-file-list>
	  <listener>
	    <listener-class>offlineUser.MyServletContextListener</listener-class>
	  </listener>
	  <listener>
	    <listener-class>offlineUser.User</listener-class>
	  </listener>
	  <servlet>
	    <description></description>
	    <display-name>LoginServlet</display-name>
	    <servlet-name>LoginServlet</servlet-name>
	    <servlet-class>offlineUser.LoginServlet</servlet-class>
	  </servlet>
	  <servlet-mapping>
	    <servlet-name>LoginServlet</servlet-name>
	    <url-pattern>/Login</url-pattern>
	  </servlet-mapping>
	  <servlet>
	    <description></description>
	    <display-name>deleteServlet</display-name>
	    <servlet-name>deleteServlet</servlet-name>
	    <servlet-class>offlineUser.deleteServlet</servlet-class>
	  </servlet>
	  <servlet-mapping>
	    <servlet-name>deleteServlet</servlet-name>
	    <url-pattern>/deleteuser</url-pattern>
	  </servlet-mapping>
	</web-app>