实现会话跟踪时出现 NullPointerException
Posted
技术标签:
【中文标题】实现会话跟踪时出现 NullPointerException【英文标题】:NullPointerException when implementing session tracking 【发布时间】:2013-06-27 09:23:21 【问题描述】:您好,我正在使用 HttpServlets 练习会话跟踪。 我在此代码中(在 else 块中)收到错误空指针异常。谁能帮帮我吗?谢谢
@WebServlet(name = "SessionTracking", urlPatterns = "/SessionTracking")
public class SessionTracking extends HttpServlet
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);
Integer counter = (Integer)session.getAttribute("sessionCounter");
if (session.isNew())
counter = new Integer(1);
session.setMaxInactiveInterval(10);
else
counter = new Integer(counter.intValue() + 1);//nullPointerException Here
session.setAttribute("sessionCounter", counter);
try
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet SessionTracking</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Session Tracking: </h1>");
out.println("<p>You have visited this page <b>" + counter + "</b> times</p>");
out.println("<h3>Session Data: </h3>");
out.println("New Session: " + session.isNew() + "<br/>");
out.println("Session ID: " + session.getId());
out.println("</body>");
out.println("</html>");
finally
out.close();
【问题讨论】:
【参考方案1】:根据session.isNew()
,即使会话不是新的,session.getAttribute("sessionCounter")
似乎也会返回 null。尝试用counter == null
替换session.isNew()
,看看它是否有效。效果应该是一样的。
【讨论】:
不,强制转换为 null 不会引发异常。以上是关于实现会话跟踪时出现 NullPointerException的主要内容,如果未能解决你的问题,请参考以下文章