在浏览器中运行servlet时出现空指针异常

时间:2013-06-25 14:13:16

标签: java servlets tomcat7

我想显示存储在浏览器上的所有cookie但获取空指针异常

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DisplayCookie extends HttpServlet{

    public void doGet(HttpServletRequest req,HttpServletResponse res)throws     IOException,ServletException{

    Cookie[] c=req.getCookies();
    res.setContentType("text/html");
    PrintWriter pw=res.getWriter();
    int i=0;
    while(i  < c.length){
        String cname=c[i].getName();
        String cvalue=c[i].getValue();
        pw.println("name="+cname+" ;value="+cvalue);
        i++;
        }
    pw.close();
    }
}

我该如何解决这个问题?

我正在获得像这样的堆栈跟踪。

 HTTP Status 500 -
 type Exception report message
 description The server encountered an internal error that prevented it from fulfilling this request.

exception
java.lang.NullPointerException

DisplayCookie.doGet(DisplayCookie.java:14)

javax.servlet.http.HttpServlet.service(HttpServlet.java:621)

javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

1 个答案:

答案 0 :(得分:2)

来自docs

  

返回:   此请求中包含的所有Cookie的数组,如果请求没有Cookie,则 null

使用保护语句检查括起while循环:

if (c != null) {
   while(i<c.length) {
    ...
   }
}