Question

hi I am practicing session tracking with HttpServlets. I get an error null pointer exception in this code (in the else block). Can anyone please help me? Thanks

@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();
    }
}
Was it helpful?

Solution

It seems that session.getAttribute("sessionCounter") is returning a null even when the session is not new according to session.isNew(). Try replacing session.isNew() with counter == null and see if it works. The effect should be the same.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top