一、session簡介
sessiond對象主要的作用是用於完成用戶的登錄、註銷等操作,每一個session對象都表示不同的訪問用戶。Session對象是javax.servlet.http.HttpSession接口的實例化對象。常用的方法有:
No | 方法 | 描述 |
1 | Public String getId() | 取得id |
2 | Public long getCreationTime() | 取得創建時間 |
3 | Public long getLastAccessedTime() | 取得最後一次操作時間 |
4 | Public Boolean isNew() | 判斷是否是新的用戶 |
5 | Public void invalidate() | 讓session失效 |
6 | Public Enumeration getAttributeNames() | 得到全部屬性名稱 |
二、取得session Id
<%@ pagecontentType="text/html" pageEncoding="GBK"%> <html> <head> <title>session id</title> </head> <body> <% String id =session.getId(); //取得session id %> <h2>SESSIONID:<%=id%></h2> <h2>SESSION ID長度:<%=id.length()%></h2> </body> </html>
三、登錄及註銷(重要)
1.登錄及註銷
login.jsp:
完成登錄表單的顯示,同時向本表單提交數據。如果登錄成功,則保存屬性;若失敗,則顯示登錄失敗信息。
welcome.jsp:
用戶登錄成功後纔可以顯示的信息,如果沒有登錄,則要給出未登錄的提示信息,同時給出登錄連接地址。
logout.jsp:
完成登錄的註銷,註銷後頁面跳轉回login.jsp頁面。
例登錄系統示例
login.jsp:
<%@ page contentType="text/html" pageEncoding="GBK"%> <html> <head> <title>session login</title> </head> <body> <form action="login.jsp" medthod="post"> 用戶名:<input type="text" name="uname"><br> 密 碼:<input type="password" name="upass"><br> <input type="submit" vlaue="登錄"> <input type="reset" value="重置"> </form> <% //假設用戶名abc 密碼123 String name = request.getParameter("uname"); // String password = request.getParameter("upass"); //用戶名和密碼的驗證 if( !(null == name || "".equals(name) || null == password || "".equals(password)) ){ if( "abc".equals(name) && "123".equals(password) ){ //定時跳轉 response.setHeader("refresh", "2; URL=welcome.jsp"); //將登錄的用戶名保存在session中 session.setAttribute("userid", name); %> <h2>用戶登錄成功,兩秒後跳轉歡迎頁面!</h2> <h2>如果沒有跳轉請按<a href="welcome.jsp">這裏</a>!</h2> <% }else{ %> <h2>用戶名或密碼輸入錯誤!</h2> <% } } %> </body> </html>
welcome.jsp:
<%@ page contentType="text/html" pageEncoding="GBK"%> <html> <head> <title>welcome</title> </head> <body> <% if( null != session.getAttribute("userid") ){ %> <h2>歡迎<%=session.getAttribute("userid")%>光臨!</h2> <h2>註銷點<a href="logout.jsp">這裏</a>!</h2> <% }else{ //非法用戶 %> <h2>請先進行系統的<a href="login.jps">登錄</a>!</h2> <% } %> </body> </html>
logout.jsp:
<%@ page contentType="text/html" pageEncoding="GBK"%> <html> <head> <title>session id</title> </head> <body> <% response.setHeader("refresh", "2; URL=login.jsp"); //定時跳轉登錄頁面 session.invalidate(); //註銷 %> <h2>您已成功退出本系統,兩秒後跳轉登錄頁面!</h2> <h2>如果沒有跳轉請按<a href="login.jsp">這裏</a>!</h2> </body> </html>
2.取得用戶操作時間
<%@ page contentType="text/html" pageEncoding="GBK"%> <html> <head> <title>getTime</title> </head> <body> <% long start = session.getCreationTime(); //取得創建時間 long end = session.getLastAccessedTime(); //取得最後一次操作時間 long time = (end - start) / 1000; //計算操作時間單位爲秒 %> <h2>您已操作<%=time%>秒!</h2> </body> </html>
以上內容參考JAVAWEB開發實戰經典(名師講壇)