见下面的代码。 getSession(false)返回一个会话,但getAttribute返回null。会话已经失效(主要是因为这个方法在我正在测试的情况下被调用两次)。我正在处理的错误是username属性为null。在尝试获取用户名属性并使会话无效之前调用isRequestedSessionIdValid()更正确,还是更好地添加空检查?
这是我的代码:
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
}
}
例如,我应该将代码更改为:
if (session != null && request.isRequestedSessionIdValid()) {
String username = session.getAttribute(USER_NAME).toString();
//do stuff with username
session.invalidate();
}
或者,我应该这样做:
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?
}