JSP会话不为空 [英] JSP session is not null

查看:65
本文介绍了JSP会话不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是JSP的新手,并且在我的Web应用程序的特定页面上,我试图确定用户是否已登录.为此,我正在检查会话是否存在.如果会话不存在,那么我会将用户重定向到登录页面.

I'm newbie to JSP and on particular page of my webapp I'm trying to determine whether user is logged in. To do this, I'm checking for session existance. If session does not exist then I will redirect user to the login page.

以下代码使我感到困惑

<%
if (null == session)
    out.println("session is null");
else
    out.println("session is not null");

if (null == request.getSession(false))
    out.println("request.getSession() is null");
else
    out.println("request.getSession() is not null");
%>

在任何情况下都会产生以下输出:

under any circumstances produces the following output:

session is not null request.getSession() is not null 

即使我没有创建会话,我也不明白为什么存在该会话.如何检查用户是否已登录?

I don't understand why the session exists even when I didn't create it. How do I check whether user is logged in or not?

谢谢.

推荐答案

默认情况下,会话是通过容器为您创建的.对于JSP,请使用

by default, session is created for you by container. For JSP use

<%@ page session="false" %>

在JSP上禁用会话创建.

to disable session creation on your JSP.

为了检查用户是否存在,您需要在用户登录后在服务器端的会话中放入一些令牌/密钥.就像

In order to check if user exists, you need to put some token/key in session on server-side after user is logged in. Like

request.getSession().setAttribute("usertoken","authenticated");

在JSP上只需检查属性是否存在并且不为空

and on JSP simply check that attribute exists and not null

if ("authenticated".equals(session.getAttribute("usertoken")) {
   // do something
}

这篇关于JSP会话不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆