jsessionid是Cookie,在URL之后加上“; 以jsessionid=xxx”传递“session id”; servlet容器用于记录用户的会话,在创建回调时会自动创建,并记录用户的访问记录。
首先,JSESSIONID是用于记录用户session的Cookie,它是servlet容器(tomcat,jetty )。
什么时候种JSESSIONID
创建会话时,也就是调用request.getSession ()时,不要谈论getSession。 作为补充,访问html不会创建session。 缺省情况下,将创建JSP页。 可以在JSP页面中关闭会话的自动创建。
JSESSIONID的工作原理:
URL的改写
服务端需要在内存中创建session,然后种饼干。 除了在请求头中设置Set-Cookie外,容器(如tomcat )还具有URL重写机制。 通过在URL之后添加此机制,可以在客户端Cookie不可用时通过在jsessionid=xxx中传递session id来确保session的可用性(即使Cookie不可用) 到目前为止,基本的网络说法是一致的
但最重要的问题是,tomcat如何知道客户端Cookie不可用。 我在idea上引入了tomcat的源调试跟踪,虽然不同版本略有不同,但应该大致相同
在tomcat中,org.Apache.catalina.connector.response是response的落地类,可以用encodeRedirectURL和encoderedirerirer两种方法重写URL 以下为编码重定向器/* *
* encodethesessionidentifierassociatedwiththisresponse
* into the specified redirect URL,if necessary。
*
* @ param URL URL to be编码
* @return true if the URL was encoded
*/
@Override
publicstringencoderedirecturl{
if (可识别(至关联) URL ) ) 0
return (到编码) URL,request.getSessionInternal ().getIdInternal ) );
} else {
返回(URL;
}
}
方法注释写得很清楚,如果需要,请将会话id填充到重定向的URL中。 让我们看看isEncodeable方法。 重要的地方添加了中文评论/**
* returntrueifthespecifiedurlshouldbeencodedwith
* asessionidentifier.thiswillbetrueifallofthefollowing
* conditions are met:
*
*
therequestwearerespondingtoaskedforavalidsession *
therequestedsessionidwasnotreceivedviaacookie *
thespecifiedurlpointsbacktosomewherewithintheweb *应用程序支持服务支持服务请求
*
*
* @ paramlocationabsoluteurltobevalidated
* @ returntrueiftheurlshouldbeencoded
*/
protectedbooleanisencodeable (finalstringlocation ) {
if (位置==null ) {
返回假;
}
//isthisanintra-document reference?
if(location.startswith('# ' ) }{
返回假;
}
//areweinavalidsessionthatisnotusingcookies?
final Request hreq=request;
finalsessionsession=hreq.getsession internal (false );
if (会话==null ) {
返回假;
}
//这里其实是网络上说的客户端禁用Cookie
if (hreq.isrequestedsessionidfromcookie (() ) ) )。
返回假;
}
//is URL编码权限
//servlet 3.0后,在项目web.xml中清除并重写URL,在支持tomat7后
if (! hreq.getServletContext ().geteffectivesessiontrackingmodes )。
contains (sessiontrackingmode.URL ) }
返回假;
}
if (安全实用程序. ispackageprotectionenabled (() ) ) )。
返回(
访问控制器. do privileged (newprivilegedaction ) {
@Override
公共布尔运行
返回布尔. value of (doisencodeable (hreq,session,location );
}
() ).booleanValue ) );
} else {
//这个方法重写URL
恢复可编码(hreq,session,location );
}
}
其中调用Request对象的isRequestedSessionIdFromCookie确定客户端Cookie是否可用。 其中,读取请求中是否传递了名为JSESSIONID的Cookie的逻辑也很简单。 因此,有人说这是internet上的第一次访问,但实际上tomcat假设Cookie不可用,除非客户端传递了JSESSIONID