【原文链接】:https://blog.tecchen.tech ,博文同步发布到博客园。

由于精力有限,对文章的更新可能不能及时同步,请点击上面的原文链接访问最新内容。

欢迎访问我的个人网站:https://www.tecchen.tech

javax.servlet.http.HttpServletRequest接口有两个方法:getSession(boolean)和getSession()。

具体什么区别,跟踪源码分析下,先摆出结论:

request.getSession(true):获取session,如果session不存在,就新建一个。

reqeust.getSession(false)获取session,如果session不存在,则返回null。

Debug时,查看HttpServletRequest接口的实现类为RequestFacade。



使用Idea查看RequestFacade的代码实现,可以看出是通过Facade外观模式对org.apache.catalina.connector.Request进行了封装。

继续看getSession()的源码,其实是调用了getSession(true)。具体是调用了request.getSession(create)。

@Override
public HttpSession getSession(boolean create) { if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
} if (SecurityUtil.isPackageProtectionEnabled()){
return AccessController.
doPrivileged(new GetSessionPrivilegedAction(create));
} else {
return request.getSession(create);
}
} @Override
public HttpSession getSession() { if (request == null) {
throw new IllegalStateException(
sm.getString("requestFacade.nullRequest"));
}
// 直接调用getSession(true)
return getSession(true);
}

进入到Request.getSession(boolean),根据注释看出,create为true时,如果HttpSession不存在,会创建一个新的HttpSession。

    /**
* @return the session associated with this Request, creating one
* if necessary and requested.
*
* @param create Create a new session if one does not exist
*/
@Override
public HttpSession getSession(boolean create) {
Session session = doGetSession(create);
if (session == null) {
return null;
} return session.getSession();
}

继续进入到doGetSession(boolean create)方法,继续分析。

    protected Session doGetSession(boolean create) {

        // There cannot be a session if no context has been assigned yet
Context context = getContext();
if (context == null) {
return (null);
} // Return the current session if it exists and is valid
// 如果当前session存在且有效,返回当前session
if ((session != null) && !session.isValid()) {
session = null;
}
if (session != null) {
return (session);
} // Return the requested session if it exists and is valid
// 这里有读写锁控制并发
Manager 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
// create为false时,返回null;create为true时创建一个新的session
if (!create) {
return (null);
}
if (response != null
&& context.getServletContext()
.getEffectiveSessionTrackingModes()
.contains(SessionTrackingMode.COOKIE)
&& response.getResponse().isCommitted()) {
throw new IllegalStateException(
sm.getString("coyoteRequest.sessionCreateCommitted"));
} // Re-use session IDs provided by the client in very limited
// circumstances.
String sessionId = getRequestedSessionId();
if (requestedSessionSSL) {
// If the session ID has been obtained from the SSL handshake then
// use it.
} else if (("/".equals(context.getSessionCookiePath())
&& isRequestedSessionIdFromCookie())) {
/* This is the common(ish) use case: using the same session ID with
* multiple web applications on the same host. Typically this is
* used by Portlet implementations. It only works if sessions are
* tracked via cookies. The cookie must have a path of "/" else it
* won't be provided for requests to all web applications.
*
* Any session ID provided by the client should be for a session
* that already exists somewhere on the host. Check if the context
* is configured for this to be confirmed.
*/
if (context.getValidateClientProvidedNewSessionId()) {
boolean found = false;
for (Container container : getHost().findChildren()) {
Manager m = ((Context) container).getManager();
if (m != null) {
try {
if (m.findSession(sessionId) != null) {
found = true;
break;
}
} catch (IOException e) {
// Ignore. Problems with this manager will be
// handled elsewhere.
}
}
}
if (!found) {
sessionId = null;
}
}
} else {
sessionId = null;
}
session = manager.createSession(sessionId); // Creating a new session cookie based on that session
if (session != null
&& context.getServletContext()
.getEffectiveSessionTrackingModes()
.contains(SessionTrackingMode.COOKIE)) {
Cookie cookie =
ApplicationSessionCookieConfig.createSessionCookie(
context, session.getIdInternal(), isSecure()); response.addSessionCookieInternal(cookie);
} if (session == null) {
return null;
} session.access();
return session;
}

StandardContext跟session没有啥关系,就是学习下StandardContext的源码及ReentrantReadWriteLock。

@Override
public Manager getManager() {
Lock readLock = managerLock.readLock();
readLock.lock();
try {
return manager;
} finally {
readLock.unlock();
}
} @Override
public void setManager(Manager manager) { Lock writeLock = managerLock.writeLock();
writeLock.lock();
Manager oldManager = null;
try {
// Change components if necessary
oldManager = this.manager;
if (oldManager == manager)
return;
this.manager = manager; // Stop the old component if necessary
if (oldManager instanceof Lifecycle) {
try {
((Lifecycle) oldManager).stop();
((Lifecycle) oldManager).destroy();
} catch (LifecycleException e) {
log.error("StandardContext.setManager: stop-destroy: ", e);
}
} // Start the new component if necessary
if (manager != null) {
manager.setContext(this);
}
if (getState().isAvailable() && manager instanceof Lifecycle) {
try {
((Lifecycle) manager).start();
} catch (LifecycleException e) {
log.error("StandardContext.setManager: start: ", e);
}
}
} finally {
writeLock.unlock();
} // Report this property change to interested listeners
support.firePropertyChange("manager", oldManager, manager);
}

结论:

request.getSession(true):获取session,如果session不存在,就新建一个。

reqeust.getSession(false)获取session,如果session不存在,则返回null。

request.getSession(true/false)的区别的更多相关文章

  1. 【转】于request.getSession(true/false/null)的区别

    http://blog.csdn.net/gaolinwu/article/details/7285783 关于request.getSession(true/false/null)的区别 一.需求原 ...

  2. 关于request.getsession(true|false)

    request.getSession(true):若存在会话则返回该会话,否则新建一个会话.request.getSession(false):若存在会话则返回该会话,否则返回NULL

  3. 转:request.getSession(true)和request.getSession(false)的区别

    1.转自:http://wenda.so.com/q/1366414933061950?src=150 概括: request.getSession(true):若存在会话则返回该会话,否则新建一个会 ...

  4. request.getSession(true)和request.getSession(false)的区别

    request.getSession(true)和request.getSession(false)的区别   request.getSession(true):若存在会话则返回该会话,否则新建一个会 ...

  5. 如何获得 request, "request.getSession(true).setAttribute("a",a);"与“request.setAttribute("a",a);”区别

    protected ServletContext getServletContext() { return ServletActionContext.getServletContext();} pro ...

  6. request.getSession()、reqeust.getSession(false)和request.getSession(true)

    getSession()/getSession(true):当session存在时返回该session,否则新建一个session并返回该对象 getSession(false):当session存在 ...

  7. 对request.getSession(false)的理解(附程序员常疏忽的一个漏洞)--转

    出处:http://blog.csdn.net/xxd851116/archive/2009/06/25/4296866.aspx [前面的话] 在网上经常看到有人对request.getSessio ...

  8. 对request.getSession(false)的理解(附程序员常疏忽的一个漏洞)

    本文属于本人原创,转载请注明出处:http://blog.csdn.net/xxd851116/archive/2009/06/25/4296866.aspx [前面的话] 在网上经常看到有人对req ...

  9. request.getSession()几种获取情况之间的差异

    一.三种情况如下 HttpSession session = request.getSession(); HttpSession session = request.getSession(true); ...

随机推荐

  1. PolyCluster: Minimum Fragment Disagreement Clustering for Polyploid Phasing 多聚类:用于多倍体的最小碎片不一致聚类

    摘要 分型是计算生物学的一个新兴领域,在临床决策和生物医学科学中有着重要的应用. 虽然机器学习技术在许多生物医学应用中显示出巨大的潜力,但它们在分型中的用途尚未完全理解. 在本文中,我们研究了基于聚类 ...

  2. KbmMW 4.40.00 测试发布

    经过漫长的等待,支持移动开发的kbmmw 4.40.00 终于发布了,这次不但支持各个平台的开发, 而且增加了认证管理器等很多新特性,非常值得升级.具体见下表. 4.40.00 BETA 1 Oct ...

  3. 8-5 Navicat工具与pymysql模块

    一 Navicat 在生产环境中操作MySQL数据库还是推荐使用命令行工具mysql,但在我们自己开发测试时,可以使用可视化工具Navicat,以图形界面的形式操作MySQL数据库 需要掌握的基本操作 ...

  4. C++智能指针shared_ptr

    shared_ptr 这里有一个你在标准库中找不到的—引用数智能指针.大部分人都应当有过使用智能指针的经历,并且已经有很多关于引用数的文章.最重要的一个细节是引用数是如何被执行的—插入,意思是说你将引 ...

  5. ZOJ 3702 Gibonacci number 2017-04-06 23:28 28人阅读 评论(0) 收藏

    Gibonacci number Time Limit: 2 Seconds      Memory Limit: 65536 KB In mathematical terms, the normal ...

  6. kubernetes yaml

    apiVersion: v1 #指定api版本,此值必须在kubectl apiversion中 kind: Deployment #指定创建资源的角色/类型 metadata: #资源的元数据/属性 ...

  7. Windows和linux通过命令互传文件

    下载pscp https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html 放在Windows的c:windows/system32下 ...

  8. FTPClient用法

      某些数据交换,我们需要通过ftp来完成. sun.net.ftp.FtpClient 可以帮助我们进行一些简单的ftp客户端功能:下载.上传文件. 但如遇到创建目录之类的就无能为力了,我们只好利用 ...

  9. 关于Unity中MonoBehaviour的构造函数

    关于Unity中MonoBehaviour的构造函数 在学习Unity MVVM UI框架的时候,一不小给一个继承自MonoBehaviour类的子类编写了自定义构造函数,结果调Bug调了两个钟,特此 ...

  10. 自己从0开始学习Unity的笔记 III (C#随机数产生基础练习)

    自己开始尝试弄一下随机数,照着方法,自己做了个英雄打怪兽的测试 int heroAttack; ; ; Random attack = new Random(); //初始化一个随机数的类 heroA ...