checking session in servlet and jsp

匆匆过客 提交于 2020-01-12 07:09:34

问题


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

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

is there any way to check this.

Thanks


回答1:


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

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 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.

<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>



回答2:


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.

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


来源:https://stackoverflow.com/questions/2974274/checking-session-in-servlet-and-jsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!