Servlet中Session会话追踪的实现机制

什么是Session

因为HTTP协议是一个无状态协议,即Web应用程序无法区分收到的两个HTTP请求是否是同一个浏览器发出的。为了跟踪用户状态,服务器可以向浏览器分配一个唯一ID,并以Cookie的形式发送到浏览器,浏览器在后续访问时总是附带此Cookie,这样,服务器就可以识别用户身份。

我们把这种基于唯一ID识别用户身份的机制称为Session。每个用户第一次访问服务器后,会自动获得一个Session ID。如果用户在一段时间内没有访问服务器,那么Session会自动失效,下次即使带着上次分配的Session ID访问,服务器也认为这是一个新用户,会分配新的Session ID。一次Session会话中往往包含着若干次request请求。

获取SessionID



@WebServlet("/test.do")
public class SessionTestServlet extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("这是一个test测试");
		HttpSession session = req.getSession();
		System.out.println("sessionid是"+session.getId());
	}
}

 

HTTPSession的方法

获取HttpSession后,常见的操作方法有:

  • void setAttribute(String name, Object value):将指定Key-Value键值对,存入当前Session会话中。
  • Object getAttribute(String name):按照指定的Key从当前Session会话中获取Value,返回值为Object类型的对象,如果不存在,则返回null
  • void removeAttribute(String name)按照指定的Key从当前Session会话中删除Key-Value键值对。
  • long getCreationTime()获取当前Session会话的创建时间
  • long getLastAccessedTime():获取当前Session会话最后一次请求的访问时间
  • String getId()获取当前Session会话的SESSION ID

服务器识别Session的关键就是依靠一个名为JSESSIONIDCookie。在Servlet中第一次调用req.getSession()时,Servlet容器自动创建一个Session ID,然后通过一个名为JSESSIONIDCookie发送给浏览器!

使用Session时,由于服务器把所有用户的Session都存储在内存中,如果遇到内存不足的情况,就需要把部分不活动的Session序列化到磁盘上,这会大大降低服务器的运行效率,因此,放入Session的数据不能太大,否则会影响服务器的运行。

Session追踪机制

在Servlet中我们可以通过实现HttpSessionListener,HttpSessionAttributeListener两个接口对Session会话进行监听!

通过重写sessionCreated方法来监听会话的创建,

通过重写sessionDestroyed方法来监听会话的销毁。

通过重写attributeAdded方法来监听会话的的KV键值对的添加

通过重写attributeReplaced方法来监听会话的的KV键值对的修改

通过重写attributeRemoved方法来监听会话的的KV键值对的删除!



@WebListener
public class SessionListener implements HttpSessionListener,HttpSessionAttributeListener{
	@Override
	public void sessionCreated(HttpSessionEvent se) {
		//开始
		HttpSession currentSession = se.getSession();
		System.out.println("这是一个新的Session会话,ID是"+currentSession.getId());
		
		//统计总共的会话数
		ServletContext application = se.getSession().getServletContext();
		Integer totalCount = (Integer)application.getAttribute("total_session_count");
		
		if(totalCount==null) {
			application.setAttribute("total_session_count",1);
		}else {
			application.setAttribute("total_session_count",totalCount +1);
		}
	}
	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		System.out.println("结束销毁一个Session会话");
		ServletContext application = se.getSession().getServletContext();
		Integer totalCount = (Integer)application.getAttribute("total_session_count");
		
		if(totalCount!=null) {
			application.setAttribute("total_session_count",totalCount - 1);
		}
	}
	//添加新的KV键值对
	@Override
	public void attributeAdded(HttpSessionBindingEvent se) {
		if(se.getName().equals("isLogin")&&(boolean)(se.getValue())) {
			ServletContext application = se.getSession().getServletContext();
			Integer totalLoginCount = (Integer)application.getAttribute("total_login_count");
			
			if(totalLoginCount==null) {
				application.setAttribute("total_login_count",1);
			}else {
				application.setAttribute("total_login_count",totalLoginCount +1);
			}
		}
		
	}
	//修改KV键值对
	@Override
	public void attributeReplaced(HttpSessionBindingEvent se) {
		
	}
	//删除KV键值对
	@Override
	public void attributeRemoved(HttpSessionBindingEvent se) {
		
	}
}

特别的是需要注释里写出@WebListener来识别为监听器,可以通过Console控制台看到会话创建,以及会话总数的统计。

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值