在两个servlet之间访问Session变量

时间:2012-01-16 16:40:36

标签: java jsp servlets nullpointerexception session-variables

我有两个servlet。在第一个servlet中,我从数据库中检索userId并将其存储在此会话变量中:

String uId = function.getLogin(username, password); //method getting the id

HttpSession session = request.getSession();
session.setAttribute("userId", uId); // here I'm setting the session variable with the id

现在在第二个servlet中我想从会话变量中检索userId,但是抛出了java.lang.NullPointerException。

HttpSession session = request.getSession(true);
String uId = session.getAttribute("userId").toString();
int userId = Integer.parseInt(uId); //this is the code that I'm using in the second servlet, and throwing the NullPointerException

我做错了吗?谢谢你的帮助

2 个答案:

答案 0 :(得分:2)

您应该检查应该为您提供NPE行号的异常。就您的代码而言:

HttpSession session = request.getSession(true);

请求可以为null。这极不可能。

String uId = session.getAttribute("userId").toString();

会话可以为null。这意味着客户端不会发回会话cookie,也可能有多个前端,另一个记录了会话。我们需要更多信息才能找出问题所在。

也可能是session.getAttribute("userId")返回null。我想说这很有可能。也许这是一个调用session.setAttribute("userId", uId);的不同会话。或者,您对function.getLogin(username, password);的初始调用可能会返回null,因此您在会话中设置了null

// this is the code that [... is] throwing the NullPointerException
int userId = Integer.parseInt(uId); 

你错了。当我阅读Java 1.6代码时,parseInt永远不会抛出NPE。这是该方法的第一行:

if (s == null) {
    throw new NumberFormatException("null");
}

我打赌你的会话有问题。我建议使用调试器找出错误设置的内容。 Printf调试也会有所帮助。

答案 1 :(得分:0)

在设置属性时,必须确保最多不写入任何响应。此外,在此之后写入响应(没有例外)。