1

一旦我调用以下类的方法,它就会返回 cookie 列表,但是当我尝试从另一个类访问相同的方法时,它会返回NullPointerException.

我想原因是servletRequest但是如何解决呢?还有其他方法可以实现吗?

public class ClientFind extends ActionSupport implements ServletResponseAware,
                                                         ServletRequestAware 
{
    .....
    Cookie coockies[] = servletRequest.getCookies();
    for (int i = 0; i < coockies.length; i++) {
        if (coockies[i].getName().equalsIgnoreCase("ID")) {
            return coockies[i].getValue();
        }
    }
    return "";
}

我也使用了以下代码,但它java.lang.NullPointerException在第 4 行返回

1        BasicClientCookie cookie = new BasicClientCookie("Namez", "Tim");
2        cookie.setPath("/");
3        org.apache.http.client.CookieStore cookieStore = null;
4        cookieStore.addCookie(cookie);
5        DefaultHttpClient httpclient = new DefaultHttpClient();
4

2 回答 2

2

我对此知之甚少ServletResponse,但如果它NullPointerException困扰你,你应该考虑这样一个事实,即如果没有发送 cookie,则该getCookies()方法返回。null

请参阅http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html#getCookies()

编辑: 您在我第一次回复后添加的第二个异常很容易捕捉到。您实际上是在将值分配给第三nullcookieStore

于 2013-07-19T04:11:16.483 回答
0

我不确定它是否是您想要的,但请尝试以下代码,

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpState;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

public class GetCookiePrintAndSetValue {

  public static void main(String args[]) throws Exception {

    HttpClient client = new HttpClient();
    client.getParams().setParameter("http.useragent", "My Browser");

    GetMethod method = new GetMethod("http://localhost:8080/");
    try{
      client.executeMethod(method);
      Cookie[] cookies = client.getState().getCookies();
      for (int i = 0; i < cookies.length; i++) {
        Cookie cookie = cookies[i];
        System.err.println(
          "Cookie: " + cookie.getName() +
          ", Value: " + cookie.getValue() +
          ", IsPersistent?: " + cookie.isPersistent() +
          ", Expiry Date: " + cookie.getExpiryDate() +
          ", Comment: " + cookie.getComment());

        cookie.setValue("My own value");
      }
      client.executeMethod(method);
    } catch(Exception e) {
      System.err.println(e);
    } finally {
      method.releaseConnection();
    }
  }
}
于 2013-07-19T04:10:56.503 回答