且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在不使用Cookie API的情况下获取sessionId而不访问会话

更新时间:2022-05-26 00:41:16

对于您的代码,请不要困难,请使用 HttpServletRequest#isRequestedSessionIdValid() 而是检查请求的会话ID以及它是否有效.

As to your code, don't do it the hard way, use HttpServletRequest#getRequestedSessionId() and HttpServletRequest#isRequestedSessionIdValid() instead to check the requested session ID and if it is valid.

if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
    // The session has been expired (or a hacker supplied a fake cookie).
}

关于您的具体问题:

访问cookie的代码使会话保持活动状态并且不会超时!

不,代码不这样做.是HTTP请求本身完成的.确实,每当您不调用 getSession()之类的东西时,会话超时都不会被延迟.无论客户端是否需要代码中的会话,该请求都会在客户端触发的每个HTTP请求中被推迟.

No, the code doesn't do that. It's the HTTP request itself which does that. It is not true that whenever you don't call getSession() or something, the session timeout won't be postponed. It will be postponed on every single HTTP request fired by the client, regardless of whether you need the session in the code.

要了解会话的工作方式,您可能会发现此答案很有帮助:

To learn about how sessions work, you may find this answer helpful: How do servlets work? Instantiation, sessions, shared variables and multithreading