先看Servlet協議描述:
請看:
getSession( boolean create)方法:
javax.servlet.http.HttpServletRequest.getSession( boolean create)
Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session.
If create is false and the request has no valid HttpSession, this method returns null.
To make sure the session is properly maintained, you must call this method before the response is committed.
getSession()方法:
javax.servlet.http. HttpSession getSession();
Returns the current session associated with this request, or if the request does not have a session, creates one.
簡單的說:噹噹前Session不存在,建立並且返回.
// There cannot be a session if no context has been assigned yet
if (context == null )
return ( null );
// Return the current session if it exists and is valid
if ((session != null ) && ! session.isValid())
session = null ;
if (session != null )
return (session);
// Return the requested session if it exists and is valid
Manager manager = null ;
if (context != null )
manager = context.getManager();
if (manager == null )
return ( null ); // Sessions are not supported
if (requestedSessionId != null ) {
try {
session = manager.findSession(requestedSessionId);
} catch (IOException e) {
session = null ;
}
if ((session != null ) && ! session.isValid())
session = null ;
if (session != null ) {
session.access();
return (session);
}
}
// Create a new session if requested and the response is not committed
if ( ! create)
return ( null );
if ((context != null ) && (response != null ) &&
context.getCookies() &&
response.getResponse().isCommitted()) {
throw new IllegalStateException
(sm.getString( " coyoteRequest.sessionCreateCommitted " ));
}
// Attempt to reuse session id if one was submitted in a cookie
// Do not reuse the session id if it is from a URL, to prevent possible
// phishing attacks
if (connector.getEmptySessionPath()
&& isRequestedSessionIdFromCookie()) {
session = manager.createSession(getRequestedSessionId());
} else {
session = manager.createSession( null );
}
// Creating a new session cookie based on that session
if ((session != null ) && (getContext() != null )
&& getContext().getCookies()) {
Cookie cookie = new Cookie(Globals.SESSION_COOKIE_NAME,
session.getIdInternal());
configureSessionCookie(cookie);
response.addCookieInternal(cookie, context.getUseHttpOnly());
}
準確地講,除非你的應用完全不需要儲存狀態(無狀態應用),不然地話,只要有一個新的串連過來,web容器都需要建立Session概念,維護狀態資訊.
但是Session是什麼?Session僅僅是一個概念:"Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user."--簡單地講,儲存使用者狀態資訊.
所以說,我們完全可以根據應用的需求,定製Session的實現:
a. Session儲存到JVM內容中--Tomcat預設的實現
b. Session儲存到Cookie中--Cookie-Based Session
c. Session儲存到本地檔案--Tomcat提供的非預設實現之一
d. Session儲存到Cache Store中--比如常見的Memcached
e. Session儲存到資料庫中--比如儲存到mysql資料庫session表,中間對於活躍的Session 緩衝到cached中.
......
那麼,假如一個應用有大量一次性不同使用者的請求(僅僅是一次性的,比如上述文章描述的情境),那麼選擇c,d,e方案都能有效解決文中所描述的問題.