session何时会被创建
- 1、 请求JSP页面时自动创建session,利用request.getSession(true);语句 原因: 由于HTTP是无状态协议,这意味着每次客户端检索网页时,都要单独打开一个服务器http连接,如果我同一个浏览器,不同页面打开你的主页10次,那就要进行10次连接和断开(TCP3次握手,4次挥手),浪费系统资源,http提供了一种长连接,keep-alive,相同会话的不同请求可以用同一连接,故jsp默认创建session。而session的创建过程中会自动将sessionId写入cookie的JSESSIONID中的,这样,只要不关闭浏览器,你在同一网站的任意网页跳转,由于每次请求都会携带同一个sessionId,不会重新创建新的会话,防止创建多个会话浪费系统资源。 否则:黑客利用几台主机,疯狂的点击某一个JSP页面,如果每次点击都创建一个新的会话,可能使服务器崩溃。
例子: 登录函数:
代码语言:javascript
复制
// 用户登录操作 public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("gb2312"); String account = request.getParameter("account"); consumerDao = new ConsumerDao(); ConsumerForm consumerForm = consumerDao.getConsumerForm(account); if (consumerForm == null) { request.setAttribute("information", "您输入的用户名不存在,请重新输入!"); } else if (!consumerForm.getPassword().equals(request.getParameter("password"))) { request.setAttribute("information", "您输入的登录密码有误,请重新输入!"); } else {
request.setAttribute("form", consumerForm); } RequestDispatcher requestDispatcher = request.getRequestDispatcher("dealwith.jsp"); requestDispatcher.forward(request, response); }</code></pre></div></div><p>登录主页:</p><div class="rno-markdown-code"><div class="rno-markdown-code-toolbar"><div class="rno-markdown-code-toolbar-info"><div class="rno-markdown-code-toolbar-item is-type"><span class="is-m-hidden">代码语言:</span>javascript</div></div><div class="rno-markdown-code-toolbar-opt"><div class="rno-markdown-code-toolbar-copy"><i class="icon-copy"></i><span class="is-m-hidden">复制</span></div></div></div><div class="developer-code-block"><pre class="prism-token token line-numbers language-javascript"><code class="language-javascript" style="margin-left:0"><body onselectstart="return false"> <table width="800" height="496" border="0" align="center" cellpadding="0" cellspacing="0" background="images/login.jpg"> <tr> <td valign="top"> <table width="658" border="0"> <tr> <td colspan="2">&nbsp;</td> </tr> <tr> <td width="92" height="358">&nbsp;</td> <td width="550" valign="bottom"> <form name="form1" method="post" action="ConsumerServlet?method=0&sign=0" onSubmit="return userCheck()"> <table width="291" border="0" align="center" cellpadding="0" cellspacing="0"> <tr> <td width="66" height="30">用户名:</td> <td width="225"><input name="account" type="text" class="inputinput" id="account" size="30"></td> </tr> <tr> <td height="30">密&nbsp;&nbsp;码:</td> <td><input name="password" type="password" class="inputinput" id="password" size="30"></td> </tr> <tr> <td height="30" colspan="2" align="center"><input type="image" class="inputinputinput" src="images/land.gif"> &nbsp;&nbsp; <a href="#" onClick="javascript:document.form1.reset()"><img src="images/reset.gif"></a> &nbsp;&nbsp; <a href="consumer/accountAdd.jsp"><img src="images/register.gif"></a></td> </tr> </table> </form> </td> </tr> </table> </td> </tr> </table>
</body>