Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Servlet學習(六)Session

Servlet學習(六)Session

編輯:關於Android編程

與Cookie相似,session也是用來記錄數據和狀態的。

不同在與,cookie記錄數據在客戶端,session記錄數據在服務器端。通過每個浏覽器的特定編號。

(重點)session的兩種實現方式:

1. 通過Cookie實現。(如果浏覽器設置為支持Cookie,則默認為這種方式)

將session的ID存在Cookie裡。

測試程序:

package com.vin.session;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 演示Servlet API中的session管理機制(常用方法)
 * 創建一個session
 * @author Pigeon
 *
 */
public class SessionInfoServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        // Returns the current session associated with this request, or if the request does not have a session, creates one. 
        HttpSession mySession = request.getSession(true);
        
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String title = "Session Info Servlet";
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Session Info Servlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h3>Session Infomation</h3>");
        
        // Returns true if the client does not yet know about the session or if the client chooses not to join the session. 
        out.println("New Session:" + mySession.isNew() + "<br>");
        // Returns a string containing the unique identifier assigned to this session.
        out.println("Session Id:" + mySession.getId() + "<br>");
        // Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. 
        out.println("Session Create Time:" + new Date(mySession.getCreationTime()) + "<br>");
        out.println("Session Last Access Time:" + new Date(mySession.getLastAccessedTime()) + "<br>");
        
        out.println("<h3>Request Infomation</h3>");
        // Returns the session ID specified by the client.
        out.println("Session Id From Request:" + request.getRequestedSessionId() + "<br>");
        // Checks whether the requested session ID came in as a cookie. 
        out.println("Session Id Via Cookie:" + request.isRequestedSessionIdFromCookie() + "<br>");
        // Checks whether the requested session ID came in as part of the request URL. 
        out.println("Session Id Via URL:" + request.isRequestedSessionIdFromURL() + "<br>");
        // Checks whether the requested session ID is still valid. 
        out.println("Valid Session Id:" + request.isRequestedSessionIdValid() + "<br>");
        
        out.println("<a href=" + response.encodeURL("SessionInfoServlet") + ">refresh</a>");
        out.println("</body></html>");
        out.close();
    }

}

創建了一個session,帶有一個唯一的sessionId,儲存在cookie裡,通過ShowCookies查看。

\

\

 

 

2. 通過URL重寫來實現。(浏覽器不支持cookie)

就是將一些額外數據(標志符)追加在表示會話的每個URL末尾,服務器在該標志符與其存儲的有關該會話的數據之間,建立對應關聯。如hello.jsp?jsessionid=1234

response.encodeURL()

 

轉碼URL後加入SessionId 測試程序: 將IE的Cookie禁用,再次運行上面的程序。點擊refresh後,發現url後被加上了jsessionid   ---------------------------------------------------------------------------------------------------------------------------------------- session以“name-value”對的形式在服務器的內存中存儲數據 session.getAttribute(String name); session通過name拿到value session.setAttribute(String name, Object value); session設置名值對。 注意:name永遠是String,value是Object,因此需要類型轉換。
package com.vin.session;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Session追蹤
 * 如果浏覽器支持Cookie,創建Session的時候會把SessionId保存在Cookie中
 * 否則必須自己編程使用URL重寫的方式實現Session:response.encodeURL()
 * @author jukey
 *
 */

public class ShowSession extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        response.setContentType("text/html;charset=gb2312");
        PrintWriter out = response.getWriter();
        String str = "Session Tracking Example";
        String heading;
        
        // 如果會話已經存在,則返回一個HttpSession;否則創建一個新的
        HttpSession session = request.getSession(true);
        // 從當前session中讀取屬性accessCount的值
        Integer accessCount = (Integer)session.getAttribute("accessCount");
        if(accessCount == null) {
            accessCount = new Integer(0);
            heading = "Welcome newUser";
        } else {
            heading = "Welcome Back";
            accessCount = new Integer(accessCount.intValue() + 1);
        }
        // 向當前session中插入鍵(key,屬性)值(value)對
        // Binds an object to this session, using the name specified.
        session.setAttribute("accessCount", accessCount);
        
        out.println("
" + "" + heading + "
" + "

Information on Your Session


" + "/n" + "/n" + "/n" + "/n" + "/n" + "/n" + "/n" + "/n" + "/n" + "/n" + "/n" + "/n" + "/n" + "/n" + ""); } }結果: \
\ \ 每次刷新,number of access +1。     web.xml



	
    index.jsp
  	

	
		HW
		com.vin.servlet.HelloWorldServlet
	

	
		HW
		/abc
	

	
		TestLifeCycleServlet
		com.vin.servlet.TestLifeCycleServlet
	

	
		TestLifeCycleServlet
		/def
	

	
		ThreeParams
		com.vin.servlet.ThreeParams
	

	
		ThreeParams
		/servlet/ThreeParams
	

	
		ShowParameters
		com.vin.servlet.ShowParameters
	

	
		ShowParameters
		/servlet/ShowParameters
	

	
		SetCookies
		com.vin.cookie.SetCookies
	

	
		SetCookies
		/servlet/SetCookies
	

	
		ShowCookies
		com.vin.cookie.ShowCookies
	

	
		ShowCookies
		/servlet/ShowCookies
	
	
	
		SessionInfoServlet
		com.vin.session.SessionInfoServlet
	

	
		SessionInfoServlet
		/servlet/SessionInfoServlet
	
	
	
		ShowSession
		com.vin.session.ShowSession
	

	
		ShowSession
		/servlet/ShowSession
	

   

 

Info Type Value" + "
" + " ID " + session.getId() +" CreatTime " + new Date(session.getCreationTime()) +" LastAccessTime " + new Date(session.getLastAccessedTime()) +" Number of Access " + accessCount +"
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved