request.getCookies()抛出NullPointerException

时间:2014-05-06 13:59:07

标签: java servlets nullpointerexception

我有简单的代码,我只是在一个servlet中设置一个cookie,然后尝试在另一个servlet中输出它,但不知怎的,我无法在另一个页面中检索cookie。

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    int life = 3600;
    Cookie para = new Cookie("para1","someValue");
    para.setMaxAge(life);
    response.addCookie(para);
    response.sendRedirect("/HelloWorld2/EndServlet");
}

//EndServlet code:


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    Cookie[] cookie = request.getCookies();

    if (cookie!=null)
        for (Cookie c : cookie)
            if(c.getName().equalsIgnoreCase("para1"))
                out.println("<html><head/><body><h1>"+c.getValue()+"</h1></body></html>");
}

0 个答案:

没有答案