2012-01-16 30 views
-1

我有两个servlet。在第一个servlet,我从数据库中检索用户标识和它存储在这个会话变量:访问两个servlet之间的会话变量

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我想要从会话变量,用户id,但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 

我正在做错什么事吗?感谢您的帮助

+0

您可以在投射前检查/打印'uId'的值吗? – Viruzzo 2012-01-16 16:43:45

+0

servlet是否在同一个webapp中?您是否使用相同的浏览器来调用这两个servlet。两次通话之间等待多少时间?为什么你不使用Integer来处理userId,因为它似乎是一个Integer? – 2012-01-16 16:45:39

+0

如果此客户端尚不存在,它只会创建一个新会话。 – 2012-01-16 16:46:34

回答

0

在设置属性时,您必须确保一直写入响应。此外,在此之后,回复写入(没有例外)。

2

你应该检查应该给你NPE行号的异常。根据您的代码:

HttpSession session = request.getSession(true); 

请求可能为空。这是极不可能的。

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

会话可能为空。这意味着客户端不会返回会话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调试也有帮助。