Reputation: 23
String id = req.getSession().getAttribute("user_id").toString();
int user_id=Integer.parseInt(id);
The error :
Cannot invoke "Object.toString()" because the return value of "javax.servlet.http.HttpServletRequest.getAttribute(String)" is null
I have also tried
String id = (String)req.getSession().getAttribute("user_id");
int user_id=Integer.parseInt(id);
The error:
class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')
Upvotes: 0
Views: 527
Reputation: 65034
It seems the attribute is either an Integer
value or is null
.
Try something like the following:
Integer id = (Integer)req.getSession().getAttribute("user_id");
if (id != null) {
int user_id = id;
// code that uses user_id ...
}
else {
// handle the case that there is no user ID.
}
Upvotes: 0