Java 在 servlet 和 jsp 中检查会话

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2974274/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:06:44  来源:igfitidea点击:

checking session in servlet and jsp

javajspsessionservlets

提问by ajay

In my web application i neet to check session already exist or not.

在我的 Web 应用程序中,我需要检查会话是否已经存在。

i want to check this in my servlet and in jsp also.

我也想在我的 servlet 和 jsp 中检查这个。

is there any way to check this.

有什么办法可以检查这个。

Thanks

谢谢

采纳答案by BalusC

You can test it with HttpServletRequest#getSession(boolean create)with create=false. It will return null if not created yet.

您可以HttpServletRequest#getSession(boolean create)使用create=false. 如果尚未创建,它将返回 null。

HttpSession session = request.getSession(false);
if (session == null) {
    // Session is not created.
} else {
    // Session is already created.
}

If you actually want to create the session anyway if it doesn't exist, then just grab it and test the freshness using HttpSession#isNew():

如果您确实想创建会话(如果它不存在),那么只需抓住它并使用HttpSession#isNew()以下命令测试新鲜度:

HttpSession session = request.getSession();
if (session.isNew()) {
    // Session is freshly created during this request.
} else {
    // Session was already created during a previous request.
}

That was how you would do it in a Servlet. In a JSP you can only test the freshness with help of JSTL and EL. You can grab the session by PageContext#getSession()and then just call isNew()on it.

这就是您在 Servlet 中的做法。在 JSP 中,您只能借助 JSTL 和 EL 来测试新鲜度。您可以通过获取会话PageContext#getSession(),然后调用isNew()它。

<c:if test="${pageContext.session.new}">
    <p>Session is freshly created during this request.</p>
</c:if>

or

或者

<p>Session is ${pageContext.session.new ? 'freshly' : 'already'} created.</p>

回答by Shashank T

One way is to set a session id in the jsp and then check the same session id in the other jsp or servlet to check if it is alive or not.

一种方法是在 jsp 中设置一个会话 id,然后在另一个 jsp 或 servlet 中检查相同的会话 id 以检查它是否处于活动状态。

HttpSession session = req.getSession();
        session.getId();