关于session的创建时间

今天看了Cookie和Session专题,里面讲到了session的创建时间。说直到server端调用HttpServletRequest.getSession(true)时才会创建session,并不是一有客户端访问时就创建。针对这一问题,以前也没深入研究,于是今天做了一个实验。如下所示:
TestServlet:
public class Test extends HttpServlet {

protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("test");
}

}

SessionListener:
public class SessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent arg0) {

System.out.println("session is created");

}

public void sessionDestroyed(HttpSessionEvent arg0) {
System.out.println("session is destory");

}

}

当在浏览器中访问TestServlet时,并没有打印出session is created,说明此时session没有被创建,如果在TestServelt中加上HttpSession session = request.getSession(true);这句时,tomcat控制台打印出打印出session is created,说明此时已经创建了session。
而jsp和servlet也有不同的处理方式,我重启服务器,在浏览器访问index.jsp时,后台打印出了打印出session is created,说明客户端第一次访问jsp页面时就创建了session,原因是jsp的内置对象session,当容器把jsp翻译成servlet类时,会生成pageContext.getSession()代码。
下面是jsp对应servlet的部分源码
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {

PageContext pageContext = null;
[color=darkred]HttpSession session = null;[/color].....


try {
response.setContentType("text/html;charset=UTF-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
[color=red]session = pageContext.getSession();[/color]
out = pageContext.getOut();
_jspx_out = out;
......}

当我访问静态页面index.html时,session并没有创建。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值