实现会话跟踪时出现NullPointerException

时间:2013-06-29 20:33:03

标签: java servlets sessiontracking

嗨,我正在使用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 个答案:

答案 0 :(得分:1)

根据session.getAttribute("sessionCounter"),即使会话不是新的,session.isNew()似乎也会返回null。尝试将session.isNew()替换为counter == null,看看它是否有效。效果应该是一样的。