我无法检索可用的cookie列表

时间:2013-07-19 03:59:28

标签: java java-ee cookies struts2

一旦我调用了下面的类的方法,它就会返回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 "";
}

我还使用了以下代码,但它在第4行重新java.lang.NullPointerException

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();

2 个答案:

答案 0 :(得分:2)

我对ServletResponse知之甚少,但如果NullPointerException困扰您,您应该考虑getCookies()方法返回null的事实。没有发送的cookies。

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

修改 您在第一次回复后添加的第二个例外很容易被捕获。您实际上是在第三行将值null分配给cookieStore

答案 1 :(得分: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();
    }
  }
}