1
創建和獲取客戶的會話
setAttribute()與getAttribute()
session.setAttribute(String name , Object obj)
如session.setAttribute("username" , "陳帝求")
將一個字符串"陳帝求"放置到session對象中,並且變量名叫username
session.getAttribute(String name) 該函數返回的是一個Object,是一個對象。
例子
String user = (String)session.getAttribute("username");
String user1= session.getAttribute("username").toString();
2
從會話中移除指定對象
session.removeAttribute(String name);
例如session.removeAttribute("username");
3
設置session有效時間
因為服務器都是給客戶端在服務器端創建30分鍾的session,所以必須設置有效時間來釋放沒有必要的會話
session.setMaxInactiveInterval(int time);
如session.setMaxInactiveInterval(3600); //設置了3600秒 就是一個小時的有效時間
4
session銷毀
session.invalidate();
5
應用session對象實現用戶登錄
服務器需要用session來記錄客戶端的登錄的狀態,都是通過session來記錄用戶狀態
1
index.jsp創建一個基本的登錄頁面 action="deal.jsp"
<body>
<form name="form1" method="post" action="deal.jsp">
用戶名: <input name="username" type="text" id="name" style="width: 120px"><br>
密 碼: <input name="pwd" type="password" id="pwd" style="width: 120px"> <br>
<br>
<input type="submit" name="Submit" value="登錄">
</form>
</body>
2
deal.jsp中創建了判斷標准,我預先設置了3個2維數組,在沒有數據庫的情況下,先將就一下吧
<%
String[][] userList={{"cdq","123"},{"sss","111"},{"aaa","111"}}; //定義一個保存用戶列表的二維組
boolean flag=false; //登錄狀態
request.setCharacterEncoding("GB18030"); //設置編碼
String username=request.getParameter("username"); //獲取用戶名
String pwd=request.getParameter("pwd"); //獲取密碼
for(int i=0;i<userList.length;i++)
{
if(userList[i][0].equals(username))
{ //判斷用戶名
if(userList[i][1].equals(pwd))
{ //判斷密碼
flag=true; //表示登錄成功
break;//跳出for循環
}
}
}
if(flag){ //如果值為true,表示登錄成功
session.setAttribute("username",username);//保存用戶名到session范圍的變量中
response.sendRedirect("main.jsp"); //跳轉到主頁
}else{
response.sendRedirect("index.jsp"); //跳轉到用戶登錄頁面
}
%>
3 main.jsp
<%
String username=(String)session.getAttribute("username"); //獲取保存在session范圍內的用戶名
%>
<body>
您好![<%=username %>]歡迎您訪問!<br>
<a href="exit.jsp">[退出]</a>
</body>
4
exit.jsp
<%
session.invalidate();//銷毀session
response.sendRedirect("index.jsp");//重定向頁面到index.jsp
%>