什么是Session

对Tomcat而言,Session是一块在服务器开辟的内存空间,其存储结构为ConcurrentHashMap;
Session的目的
Http协议是一种无状态协议,即每次服务端接收到客户端的请求时,都是一个全新的请求,服务器并不知道客户端的历史请求记录;
Session的主要目的就是为了弥补Http的无状态特性。简单的说,就是服务器可以利用session存储客户端在同一个会话期间的一些操作记录;
实现机制
先看两个问题,如下:
1、服务器如何判断客户端发送过来的请求是属于同一个会话?
答:用Session id区分,Session id相同的即认为是同一个会话,在Tomcat中Session id用JSESSIONID表示;
2、服务器、客户端如何获取Session id?Session id在其之间是如何传输的呢?
答:服务器第一次接收到请求时,开辟了一块Session空间(创建了Session对象),同时生成一个Session id,并通过响应头的Set-Cookie:“JSESSIONID=XXXXXXX”命令,向客户端发送要求设置cookie的响应;
客户端收到响应后,在本机客户端设置了一个JSESSIONID=XXXXXXX的cookie信息,该cookie的过期时间为浏览器会话结束;
接下来客户端每次向同一个网站发送请求时,请求头都会带上该cookie信息(包含Session id);
然后,服务器通过读取请求头中的Cookie信息,获取名称为JSESSIONID的值,得到此次请求的Session id;
ps:服务器只会在客户端第一次请求响应的时候,在响应头上添加Set-Cookie:“JSESSIONID=XXXXXXX”信息,接下来在同一个会话的第二第三次响应头里,是不会添加Set-Cookie:“JSESSIONID=XXXXXXX”信息的;
而客户端是会在每次请求头的cookie中带上JSESSIONID信息;
举个例子:
以chrome浏览器为例,访问一个基于tomcat服务器的网站的时候,
浏览器第一次访问服务器,服务器会在响应头添加Set-Cookie:“JSESSIONID=XXXXXXX”信息,要求客户端设置cookie,如下图:
同时我们也可以在浏览器中找到其存储的sessionid信息,如下图
接下来,浏览器第二次、第三次...访问服务器,观察其请求头的cookie信息,可以看到JSESSIONID信息存储在cookie里,发送给服务器;且响应头里没有Set-Cookie信息,如下图:
只要浏览器未关闭,在访问同一个站点的时候,其请求头Cookie中的JSESSIONID都是同一个值,被服务器认为是同一个会话。
再举个简单的例子加深印象,新建个Web工程,并写一个Servlet,在doGet中添加如下代码,主要做如下工作
首先,从session中获取key为count的值,累加,存入session,并打印;
然后,每次从请求中获取打印cookie信息,从响应中获取打印Header的Set-Cookie信息:
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getSession().getAttribute("count") == null){
request.getSession().setAttribute("count", 0);
response.getWriter().write(0+"");
}else{
int a = Integer.parseInt(request.getSession().getAttribute("count").toString());
request.getSession().setAttribute("count", ++a);
response.getWriter().write(a+"");
}
Cookie[] cookies = request.getCookies();
StringBuffer sb = new StringBuffer();
if(cookies!=null){
for(Cookie cookie : cookies){
sb.append(cookie.getName()+":"+cookie.getValue()+",");
}
sb.deleteCharAt(sb.length()-1);
}
System.out.println("[第"+(++index)+"次访问]from client request, cookies:" + sb);
System.out.println("[第"+(index)+"次访问]from server response, header-Set-Cookie:" + response.getHeader("Set-Cookie"));;
}
部署到tomcat后,连续访问该servlet,观察控制台输出,如下,客户端第一次访问服务器的时候,在服务端的响应头里添加了JSESSIONID信息,且接下来客户端的每次访问都会带上该JSESSIONID:
其实这里有一个问题,session劫持
只要用户知道JSESSIONID,该用户就可以获取到JSESSIONID对应的session内容,还是以上面这个例子为例,
我先用IE浏览器访问该站点,比如连续访问了5次,此时,session中的count值为:
查看该会话的Session id,为6A541281A79B24BC290ED3270CF15E32
接下来打开chrome控制台,将IE浏览器获取过来的JSESSIONID信息(“6A541281A79B24BC290ED3270CF15E32”)写入到cookie中,如下
接着删除其中的一个,只留下JSESSIONID为“6A541281A79B24BC290ED3270CF15E32”的cookie;
刷新页面,发现我们从session获取的count值已经变成6了,说明此次chrome浏览器的请求劫持了IE浏览器会话中的session,
Tomcat中的session实现
Tomcat中一个会话对应一个session,其实现类是StandardSession,查看源码,可以找到一个attributes成员属性,即存储session的数据结构,为ConcurrentHashMap,支持高并发的HashMap实现;
/** * The collection of user data attributes associated with this Session. */ protected Map<String, Object> attributes = new ConcurrentHashMap<String, Object>();
那么,tomcat中多个会话对应的session是由谁来维护的呢?ManagerBase类,查看其代码,可以发现其有一个sessions成员属性,存储着各个会话的session信息:
/** * The set of currently active Sessions for this Manager, keyed by * session identifier. */ protected Map<String, Session> sessions = new ConcurrentHashMap<String, Session>();
接下来,看一下几个重要的方法,
服务器查找Session对象的方法
客户端每次的请求,tomcat都会在HashMap中查找对应的key为JSESSIONID的Session对象是否存在,可以查看Request的doGetSession方法源码,如下源码:
protected Session doGetSession(boolean create) {
// There cannot be a session if no context has been assigned yet
Context context = getContext();
if (context == null) {
return (null);
}
// Return the current session if it exists and is valid
if ((session != null) && !session.isValid()) {
session = null;
}
if (session != null) {
return (session);
}
// Return the requested session if it exists and is valid
Manager manager = context.getManager();
if (manager == null) {
return null; // Sessions are not supported
}
if (requestedSessionId != null) {
try {
session = manager.findSession(requestedSessionId);
} catch (IOException e) {
session = null;
}
if ((session != null) && !session.isValid()) {
session = null;
}
if (session != null) {
session.access();
return (session);
}
}
// Create a new session if requested and the response is not committed
if (!create) {
return (null);
}
if ((context != null) && (response != null) &&
context.getServletContext().getEffectiveSessionTrackingModes().
contains(SessionTrackingMode.COOKIE) &&
response.getResponse().isCommitted()) {
throw new IllegalStateException
(sm.getString("coyoteRequest.sessionCreateCommitted"));
}
// Re-use session IDs provided by the client in very limited
// circumstances.
String sessionId = getRequestedSessionId();
if (requestedSessionSSL) {
// If the session ID has been obtained from the SSL handshake then
// use it.
} else if (("/".equals(context.getSessionCookiePath())
&& isRequestedSessionIdFromCookie())) {
/* This is the common(ish) use case: using the same session ID with
* multiple web applications on the same host. Typically this is
* used by Portlet implementations. It only works if sessions are
* tracked via cookies. The cookie must have a path of "/" else it
* won't be provided to for requests to all web applications.
*
* Any session ID provided by the client should be for a session
* that already exists somewhere on the host. Check if the context
* is configured for this to be confirmed.
*/
if (context.getValidateClientProvidedNewSessionId()) {
boolean found = false;
for (Container container : getHost().findChildren()) {
Manager m = ((Context) container).getManager();
if (m != null) {
try {
if (m.findSession(sessionId) != null) {
found = true;
break;
}
} catch (IOException e) {
// Ignore. Problems with this manager will be
// handled elsewhere.
}
}
}
if (!found) {
sessionId = null;
}
sessionId = getRequestedSessionId();
}
} else {
sessionId = null;
}
session = manager.createSession(sessionId);
// Creating a new session cookie based on that session
if ((session != null) && (getContext() != null)
&& getContext().getServletContext().
getEffectiveSessionTrackingModes().contains(
SessionTrackingMode.COOKIE)) {
Cookie cookie =
ApplicationSessionCookieConfig.createSessionCookie(
context, session.getIdInternal(), isSecure());
response.addSessionCookieInternal(cookie);
}
if (session == null) {
return null;
}
session.access();
return session;
}
先看doGetSession方法中的如下代码,这个一般是第一次访问的情况,即创建session对象,session的创建是调用了ManagerBase的createSession方法来实现的; 另外,注意response.addSessionCookieInternal方法,该方法的功能就是上面提到的往响应头写入“Set-Cookie”信息;最后,还要调用session.access方法记录下该session的最后访问时间,因为session是可以设置过期时间的;
session = manager.createSession(sessionId);
// Creating a new session cookie based on that session
if ((session != null) && (getContext() != null)
&& getContext().getServletContext().
getEffectiveSessionTrackingModes().contains(
SessionTrackingMode.COOKIE)) {
Cookie cookie =
ApplicationSessionCookieConfig.createSessionCookie(
context, session.getIdInternal(), isSecure());
response.addSessionCookieInternal(cookie);
}
if (session == null) {
return null;
}
session.access();
return session;
再看doGetSession方法中的如下代码,这个一般是第二次以后访问的情况,通过ManagerBase的findSession方法查找session,其实就是利用map的key从ConcurrentHashMap中拿取对应的value,这里的key即requestedSessionId,也即JSESSIONID,同时还要调用session.access方法,记录下该session的最后访问时间;
if (requestedSessionId != null) {
try {
session = manager.findSession(requestedSessionId);
} catch (IOException e) {
session = null;
}
if ((session != null) && !session.isValid()) {
session = null;
}
if (session != null) {
session.access();
return (session);
}
}
在session对象中查找和设置key-value的方法
这个我们一般调用getAttribute/setAttribute方法:
getAttribute方法很简单,就是根据key从map中获取value;
setAttribute方法稍微复杂点,除了设置key-value外,如果添加了一些事件监听(HttpSessionAttributeListener)的话,还要通知执行,如beforeSessionAttributeReplaced, afterSessionAttributeReplaced, beforeSessionAttributeAdded、 afterSessionAttributeAdded。。。
session存在的问题
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
# tomcat
# session
# 实现
# Tomcat实现session共享(session 会话复制)
# Tomcat集群和Session复制应用介绍
# 深入浅析TomCat Session管理分析
# nginx+tomcat实现负载均衡
# 使用redis session共享
# Tomcat中session的管理机制
# Java中tomcat memecached session 共享同步问题的解决办法
# 浅谈Tomcat Session管理分析
# Nginx+Tomcat关于Session的管理的实现
# Tomcat如何监控并删除超时Session详解
# Tomcat中的Session与Cookie深入讲解
# 客户端
# 会在
# 都是
# 如下图
# 为例
# 这块
# 先看
# 多台
# 有一个
# 几个
# 是一种
# 也就
# 多个
# 的说
# 是由
# 一台
# 数据结构
# 头上
# 在同一个
# 很简单
相关文章:
如何在云主机上快速搭建网站?
婚礼视频制作网站,学习*后期制作的网站有哪些?
建站之星3.0如何解决常见操作问题?
如何在建站宝盒中设置产品搜索功能?
建站主机与服务器功能差异如何区分?
如何用花生壳三步快速搭建专属网站?
攀枝花网站建设,攀枝花营业执照网上怎么年审?
学校建站服务器如何选型才能满足性能需求?
网站网页制作电话怎么打,怎样安装和使用钉钉软件免费打电话?
洛阳网站制作公司有哪些,洛阳的招聘网站都有哪些?
如何用PHP工具快速搭建高效网站?
电视网站制作tvbox接口,云海电视怎样自定义添加电视源?
高端智能建站公司优选:品牌定制与SEO优化一站式服务
电商平台网站制作流程,电商网站如何制作?
如何在阿里云ECS服务器部署织梦CMS网站?
如何配置FTP站点权限与安全设置?
如何通过老薛主机一键快速建站?
如何确保西部建站助手FTP传输的安全性?
深圳网站制作设计招聘,关于服装设计的流行趋势,哪里的资料比较全面?
重庆市网站制作公司,重庆招聘网站哪个好?
宿州网站制作公司兴策,安徽省低保查询网站?
网站建设制作需要多少钱费用,自己做一个网站要多少钱,模板一般多少钱?
车管所网站制作流程,交警当场开简易程序处罚决定书,在交警网站查询不到怎么办?
如何快速查询域名建站关键信息?
名字制作网站免费,所有小说网站的名字?
如何在万网ECS上快速搭建专属网站?
如何在橙子建站中快速调整背景颜色?
小程序网站制作需要准备什么资料,如何制作小程序?
为什么Go需要go mod文件_Go go mod文件作用说明
盐城做公司网站,江苏电子版退休证办理流程?
网站制作怎么样才能赚钱,用自己的电脑做服务器架设网站有什么利弊,能赚钱吗?
公司网站设计制作厂家,怎么创建自己的一个网站?
PHP正则匹配日期和时间(时间戳转换)的实例代码
微网站制作教程,我微信里的网站怎么才能复制到浏览器里?
学校免费自助建站系统:智能生成+拖拽设计+多端适配
c# Task.Yield 的作用是什么 它和Task.Delay(1)有区别吗
青岛网站设计制作公司,查询青岛招聘信息的网站有哪些?
网站制作的方法有哪些,如何将自己制作的网站发布到网上?
标准网站视频模板制作软件,现在有哪个网站的视频编辑素材最齐全的,背景音乐、音效等?
建站之星在线版空间:自助建站+智能模板一键生成方案
建站之星展会模版如何一键下载生成?
如何获取PHP WAP自助建站系统源码?
网站制作企业,网站的banner和导航栏是指什么?
胶州企业网站制作公司,青岛石头网络科技有限公司怎么样?
如何通过主机屋免费建站教程十分钟搭建网站?
深圳网站制作培训,深圳哪些招聘网站比较好?
网站制作大概多少钱一个,做一个平台网站大概多少钱?
建站之星安装后界面空白如何解决?
建站之星多图banner生成与模板自定义指南
如何快速选择适合个人网站的云服务器配置?
*请认真填写需求信息,我们会在24小时内与您取得联系。