Web服務器跟蹤客戶狀態(tài)通常有四種方法:
建立含有跟蹤數(shù)據(jù)的隱藏字段;
重寫包含額外參數(shù)的url;
使用持續(xù)的cookie;
使用Servlet API中的Session(會話機制)
Session用于跟蹤客戶的狀態(tài)。Session指的是在一段時間內(nèi),單個客戶與Web服務器的一連串相關(guān)的交互過程,在一個Session中,客戶可能會多次請求訪問同一個網(wǎng)頁,也可能請求訪問各種不同的服務器資源。
即:在會話中可能訪問a.jsp,也可能訪問servlet等。。
例子1:在電子郵件應用中,從一個客戶登錄到電子郵件系統(tǒng)開始,經(jīng)過收信,寫信,發(fā)信等一系列操作,直至最后退出郵件系統(tǒng),整個過程都是一個Session。
例子2:在購物網(wǎng)站應用中,從一個客戶開始購物,到最后結(jié)賬,整個過程為一個Session。
Session的運行機制
1、當一個session開始時,Servlet容器將創(chuàng)建一個HttpServlet對象,在HttpServlet對象中可以存放客戶的狀態(tài)信息。(例如購物車);
2、Servlet容器為HttpSession分配一個唯一的標識符,稱為Session ID。Servlet容器將Session ID作為Cookie保存在客戶的瀏覽器中。
3、每次客戶發(fā)出Http請求時,Servlet容器可以從HttpServletRequest對象中讀取Session ID ,然后根據(jù)Session ID找到相應的HttpServlet對象,從而獲取客戶額狀態(tài)信息。

HttpSession接口的一些常用方法:
session是httpSession的實例
String getId(): 返回的字符串由Servlet容器分配的。
invalidate():使當前的Session失效,Servlet容器會釋放httpServlet對象占用的資源。
getAttribute( String name, Object value)和setAttribute(String name);
boolean isNew(): 特別地,如果客戶端禁用掉cookie,則服務器會new 一個新的sessionid。
void setMaxInactiveInterval(int interval):以秒為單位,設(shè)置session處于不活動狀態(tài)的最大時限,負數(shù)為一直存活。
Session的生命周期:
1、當客戶第一次訪問web應用中支持Session的某個網(wǎng)頁時,就會開始一個新的session。
2、接下來當客戶瀏覽這個web應用的不同網(wǎng)頁時,始終處于同一個session中。
3、默認情況下,jsp是支持session的,也可以通過以下語句顯式聲明和支持session
<@page session = "true">
以下情況Session將結(jié)束生命后期,Servlet容器將會將Session所占用的資源放掉:
1、Session過期
2、服務器端調(diào)用的HttpSession的invalidate()方法
為什么說瀏覽器關(guān)閉后,我們就會關(guān)閉一個session呢?
因為session存放在cookie中,會話cookie不是存放在硬盤中,存放在cookie中,關(guān)閉了瀏覽器,cookie也被關(guān)閉,無法通過cookied訪問原來的那個session,所以服務器會新開一個session。原來那個session在生命周期到后失效。
Session過期指的當session開始時,在一段時間內(nèi)客戶沒有好web服務器交互,這個session會失效,HttpSession的setMaxInactiveInteral()方法可以設(shè)置允許Session保持不活動狀態(tài)的時間(以秒為單位), 如果超過這一時間,Session就會失效。
實例:模擬一個登錄系統(tǒng);
業(yè)務邏輯:如果登錄成果則添加user到session里面,且轉(zhuǎn)到index.jsp,如果是管理員則可以看見修改功能。不是的話只能看見查詢功能。服務器端也做相應的處理,如果沒有登錄的用戶就轉(zhuǎn)到登錄界面。
如果登錄失敗就轉(zhuǎn)回登錄界面并且把填寫的信息返回。
1、login.jsp
<form action="/Email/userLoginServlet" method="post">
用戶名:<input type="text" name="username" value="<%=null == request.getAttribute("username") ? "":request.getAttribute("username")%>"><br>
密碼:<input type="password" name="password"><br>
權(quán)限:
<select name="authority">
<option value="1" <%="1".equals(request.getAttribute("authority"))? "selected":""%>>普通用戶</option>
<option value="2" <%="2".equals(request.getAttribute("authority"))? "selected":""%>>管理員</option>
</select><br>
<input type="submit" value="提交">
</form>
2、userLoginServlet.servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = "";
String password = "";
String authority = "";
HttpSession session = request.getSession();
username = request.getParameter("username");
password = request.getParameter("password");
authority = request.getParameter("authority");
if ( "1".equals(authority) )
{
if( "zhangsan".equals(username) && "123456".equals(password) )
{
addSession(username, password, authority, session);
}
else {
userError(request, response, username, authority);
}
}
else if( "2".equals(authority) )
{
if ("lisi".equals(username) && "654321".equals(password) )
{
addSession(username, password, authority, session);
}
else {
userError(request, response, username, authority);
}
}
else
{
userError(request, response, username, authority);
}
RequestDispatcher rd = request.getRequestDispatcher("sesion/index.jsp");
rd.forward(request, response);
}
private void userError(HttpServletRequest request, HttpServletResponse response, String username, String authority)
throws ServletException, IOException {
request.setAttribute("username", username);
request.setAttribute("authority", authority);
RequestDispatcher rd = request.getRequestDispatcher("sesion/login.jsp");
rd.forward(request, response);
}
private void addSession(String username, String password, String authority,HttpSession session) {
User user = new User();
user.username = username;
user.password = password;
user.authority = authority;
session.setAttribute("user", user);
}
private void userError(String username,String authority,HttpServletResponse response) {
try {
response.sendRedirect("http://localhost:8080/Email/sesion/login.jsp?error=true&username="+username+"autority="+authority);
} catch (IOException e) {
e.printStackTrace();
}
}
}
3、index.jsp
<body>
<% User user = new User();
user = (User)session.getAttribute("user");
if( null == user ) {
%>
<jsp:forward page="sesion/login.jsp"/>
<% } %>
<table>
<tr><td><a href="/Email/QueryServlet">查詢</a></td>
<%if( "2".equals(user.getAuthority())) {
%>
<td><a href="/Email/UpdateServlet">修改</a></td>
<%} %>
</tr>
</table>
</body>
3、(queyServlet省略、updateServlet)
User user = new User();
HttpSession session = request.getSession();
user = (User)session.getAttribute("user");
if( null == user ) {
RequestDispatcher rd = request.getRequestDispatcher("sesion/login.jsp");
rd.forward(request, response);
return;
}
if( "1".equals(user.authority) ) {
System.out.println("沒有權(quán)限");
}
System.out.println("成功");
}