-1

我想显示存储在浏览器上的所有 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)
4

1 回答 1

2

文档

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

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

if (c != null) {
   while(i<c.length) {
    ...
   }
}
于 2013-06-25T14:16:16.237 回答