概述:因为HTTP协议是一个无状态协议,即web应用程序无法区分收到的两个http请求时否时同一个浏览器发出的,为了追踪追踪用户状态,服务器可以向浏览器分配一个唯一的ID,并以Cookie的形式发送到浏览器,浏览器在后续访问时总是附带此Cookie,这样,服务器就可以识别用户身份。若长时间未访问,Session会自动失效,一次Session会话中往往包含着若干次request请求。
获取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的关键就是依靠一个名为JSESSIONID的Cookie。在Servlet中第一次调用req.getSession()时,Servlet容器自动创建一个Session ID,然后通过一个名为SESSIONID的Cookie发送给浏览器
以下是通过HttpSessionListener,HttpSessionAttributeListener对Session会话进行的操作
package com.cuihua1;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener
public class SessionListener implements HttpSessionListener,HttpSessionAttributeListener{
//开始会话
@Override
public void sessionCreated(HttpSessionEvent se) {
HttpSession currentSession = se.getSession();
System.out.println("开始一个新的会话,该会话的SessionID"+ currentSession.getId());
//统计总会话数
ServletContext application = se.getSession().getServletContext();
Integer totalSessionCount = (Integer)application.getAttribute("total_session_count");
if(totalSessionCount == null) {
application.setAttribute("total_session_count",1);
}else {
application.setAttribute("total_session_count", totalSessionCount +1);
}
}
//销毁会话
@Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("销毁一个会话");
ServletContext application = se.getSession().getServletContext();
Integer totalSessionCount = (Integer)application.getAttribute("total_session_count");
if(totalSessionCount != null) {
application.setAttribute("total_session_count", totalSessionCount - 1);
}
}
//在session中添加新的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);
}
}
}
//在session中修改新的KV键值对
@Override
public void attributeReplaced(HttpSessionBindingEvent se) {
}
//在session中删除新的KV键值对
@Override
public void attributeRemoved(HttpSessionBindingEvent se) {
}
}