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

时间:2022-01-24 21:12:58

I want to display all cookies stored on browser but getting null pointer exception

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

How can i solve this problem?

我怎么解决这个问题?

I am getting stack trace like this.

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

 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 个解决方案

#1


2  

From the docs

来自文档

Returns: an array of all the Cookies included with this request, or null if the request has no cookies

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

Enclose the while loop in with a guard statement check:

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

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

#1


2  

From the docs

来自文档

Returns: an array of all the Cookies included with this request, or null if the request has no cookies

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

Enclose the while loop in with a guard statement check:

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

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