I have stored user id in Session using following command in Servlet:
HttpSession session = request.getSession();
session.setAttribute("user", user.getId());
Now, I want to access that user id from another Servlet:
HttpSession session = request.getSession(false);
int userid = (int) session.getAttribute("user"); // This is not working
OR
User user = new User();
user.setId(session.getAttribute("user")); This ain't possible (Object != int)
Question:
- How can I cast to int and send the id to DAO for SELECT statement
Even if you saved an
int, that method expects an Object so yourintwill become anIntegerdue to auto-boxing. Try to cast it back toIntegerand it should be fine:However, if the attribute is null you will get a
NullPointerExceptionhere, so maybe it’s better to go withIntegerall the way:After this, you can safely check if
useridisnull.EDIT:
In response to your comments, here’s what I mean by “check for null”.