我正在
Cannot invoke "javax.servlet.http.HttpSession.getAttribute(String)" because "session" is null
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Servlet.setContentType(request, response);
try {
HttpSession session = request.getSession(false);
if (session.getAttribute("userCategory") != null && session.getAttribute("userId") != null
&& session.getAttribute("userName") != null) {
// remove session
session.removeAttribute("userCategory");
session.removeAttribute("userId");
session.removeAttribute("userName");
session.invalidate();
// back button or F5 not show secure pages back to the user
response.setHeader("Cache-Control", "private, no-store, no-cache, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
// logout and forward a page
response.sendRedirect("/");
return;
/*
* return; <-- is important Otherwise the code will continue to run and hit some
* session.getAttribute() method further down in the block causing exactly this
* exception.
*/
}
} catch (Exception e) {
EmailErrorsToAdmin.setMsg(this.getClass().getCanonicalName(), e);
}
}
我非常抱歉,我刚刚发现这段代码抛出错误无法调用“javax.servlet.http.HttpSession.getAttribute(String)”,因为“session”为空
以前我怀疑当我创建会话时,它的抛出 Cannot invoke "javax.servlet.http.HttpSession.getAttribute(String)" 因为 "session" 为 null 但刚刚在 Logout 类中发现它给出错误
请指出我哪里出错了?
致以诚挚的问候
您删除了部分会话:
HttpSession session = request.getSession(false);
要设置某个对象的值,您需要在设置其属性“之前”创建该对象。您试图设置一个空对象然后创建它。不幸的是这是不可能的。
此外,我发现这篇文章有助于了解
之间的差异request.getSession() 和 request.getSession(true)
祝你好运!