getSession()与getSession(boolean create)区别
1. 通过HttpServletRequest的部分源码观察到
public interface HttpServletRequest extends ServletRequest {
/**
* Returns the current <code>HttpSession</code> associated with this request
* or, if there is no current session and <code>create</code> is true,
* returns a new session.
* <p>
* If <code>create</code> is <code>false</code> and the request has no valid
* <code>HttpSession</code>, this method returns <code>null</code>.
* <p>
* To make sure the session is properly maintained, you must call this
* method before the response is committed. If the container is using
* cookies to maintain session integrity and is asked to create a new
* session when the response is committed, an IllegalStateException is
* thrown.
*
* @param create
* <code>true</code> to create a new session for this request if
* necessary; <code>false</code> to return <code>null</code> if
* there's no current session
* @return the <code>HttpSession</code> associated with this request or
* <code>null</code> if <code>create</code> is <code>false</code>
* and the request has no valid session
* @see #getSession()
*/
public HttpSession getSession(boolean create);
/**
* Returns the current session associated with this request, or if the
* request does not have a session, creates one.
*
* @return the <code>HttpSession</code> associated with this request
* @see #getSession(boolean)
*/
public HttpSession getSession();
}
2. getSession(boolean create)
注解大致意思是返回一个和request相关联的session,如果没有则判断create参数,如果create为true则创建一个返回,如果create为false,则返回null;
3. getSession()
上的注解大致是返回和request相关联的session,如果不存在就创建一个;
也就是 getSession() 相当于 getSession(true);
4. 使用注意
- 存数据一般使用 getSession() 就可以。
- 取数据一般使用 getSession(false) 还要做数据的判空处理;