See code below. getSession(false) returns a session, but getAttribute returns null. The session has already been invalidated (basically because this method gets called twice in the situation I'm testing). The error that I'm dealing with is that the username attribute is null. Is it more correct to call isRequestedSessionIdValid() before trying to get the username attribute and invalidating the session, or is it better to just add a null check?
Here's my code:
public Response logout(HttpServletRequest request) {
try {
HttpSession session = request.getSession(false);
if (session != null) {
String username = session.getAttribute(USER_NAME).toString();
//do stuff with username
session.invalidate();
}
} catch (Exception e) {
//handle exception
}
}
For example, should I change my code to:
if (session != null && request.isRequestedSessionIdValid()) {
String username = session.getAttribute(USER_NAME).toString();
//do stuff with username
session.invalidate();
}
or, should I just do:
if (session != null) {
if (session.getAttribute(USER_NAME) != null) {
String username = session.getAttribute(USER_NAME).toString();
//do stuff with username
}
session.invalidate(); //Does this still need to be called?
}