嗨,我正在使用 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();
}
}