2 qq 28422323 qq_28422323 于 2015.06.14 15:50 提问

Sevlet监听器检测在线人数,出现空指针异常

监听器代码

public class UserCountListenerTest implements HttpSessionListener,ServletContextListener{
private int usercount;
private ServletContext cxt;
@Override
public void contextDestroyed(ServletContextEvent arg0) {
cxt = null;
}

public void contextInitialized(ServletContextEvent e) {
    cxt = e.getServletContext();
}


public void sessionCreated(HttpSessionEvent arg0) {
        usercount++;
        cxt.setAttribute("usercount",new Integer(usercount));
}


public void sessionDestroyed(HttpSessionEvent arg0) {
    usercount--;
    cxt.setAttribute("usercount",new Integer(usercount));
}

}
xml文件配置也没出错

下面是servlet代码

@WebServlet("/TestUserCount")
public class TestUserCount extends HttpServlet {
private static final long serialVersionUID = 1L;
public TestUserCount() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext cxt = this.getServletContext();
HttpSession session = request.getSession();

    int usercount = Integer.parseInt(cxt.getAttribute("usercount").toString());


    PrintWriter out = response.getWriter();
    out.println("<!DOCTYPE html>");
    out.println("<html>");
    out.println("<head>");
    out.println("<meta charset=\"UTF-8\">");
    out.println("<title>");
    out.println("在线人数");
    out.println("</title>");
    out.println("</head>");
    out.println("<body>");

    out.println(usercount);

    out.println("</body>");
    out.println("</html>");

    out.close();

}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request,response);
}

}

异常提示第27行(int usercount = Integer.parseInt(cxt.getAttribute("usercount").toString());)出现错误

java.lang.NullPointerException
com.lzm.countlistener.TestUserCount.doGet(TestUserCount.java:27)

2个回答

bdmh
bdmh   Ds   Rxr 2015.06.14 16:16

那估计就是没有获得 usercount属性,这个你得仔细查一下

cuiwei1026522829
cuiwei1026522829   Ds   Rxr 2015.06.14 22:03

登陆的时候要把相关信息保存在session中,这样你用的时候才会有啊,空指针,没有找到这个属性值

Csdn user default icon
上传中...
上传图片
插入图片