request.getsession(true/false)的区别_candyメ奶糖-编程思维

【原文链接】: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。

版权声明:本文版权归作者所有,遵循 CC 4.0 BY-SA 许可协议, 转载请注明原文链接
https://www.cnblogs.com/Candies/p/10635414.html

Java:会话技术、cookie和jsp-编程思维

会话技术 会话:一次会话中包含多次请求和响应。 一次会话:浏览器第一次给服务器资源发送请求,会话建立,直到有一方断开为止 功能:在一次会话的范围内的多次请求间,共享数据 方式: 客户端会话技术:Cookie 服务器端会话技术:Session Cookie: 概念:客户端会话技术,将数据保存到客户端 快速入门:

Cookie、Session和Token-编程思维

【Cookie】   Web技术发展初期,因为http协议无状态的特性,Web业务系统无法获知Client端到底做了哪些操作、谁做的操作、在什么情况下作的操作。为了解决上述业务系统遇到的难题、优化用户使用体验,cookie技术应运而生。其特点如下: 产生方式 存储位置 传输方式 典型应用 安全性 http传输效率 业务

session、token和cookie-编程思维

HTTP是无状态的,什么叫无状态?意思是HTTP不会记住用户,即使你刚刚才使用账号密码登录过系统,下一次请求,还得再次校验你的身份。 常用做身份校验的方式有session和token,他们有各自的优缺点,可能有人质疑说还有cookie,cookie只是用来存储数据的载体。 session认证机制 认证流程: 用户使用账

session()_沧海一滴-编程思维

  如何使用 Session Java Api 只给我们一种方式来 获取 当前会话相关的 session: HttpSession session = request.getSession(); //或 HttpSession session = request.getSession(boolean); 设置值:

服务器共享session的方式_范仁义-编程思维

服务器共享session的方式 简介 1. 基于NFS的Session共享NFS是Net FileSystem的简称,最早由Sun公司为解决Unix网络主机间的目录共享而研发。这个方案实现最为简单,无需做过多的二次开发,仅需将共享目录服务器mount到各频道服务器的本地session目录即可,缺点是NFS依托于复杂的安

session的生命周期是怎样的_范仁义-编程思维

session的生命周期是怎样的 一、总结 一句话总结:Tomcat中Session的默认失效时间为20分钟。如果我们敲代码的时候把它设置成1个月,那么这一个月的数据会代替默认20分钟的数据,使session的失效时间为一个月。   1、手机浏览器的session为什么会失效的很快? 绝大多数的手机浏览器都不支持Coo