检索cookie

时间:2013-01-26 19:08:10

标签: java servlets

我是servlets的新手,我对cookies有疑问。

我有一个servlet,我在其中创建一个cookie并编写一个页面,我将链接指向另一个要检索cookie的servlet。

由于某种原因,我无法检索它。有什么建议为什么它是空的?

THX

第一个servlet:

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
        // create new cookies
        Cookie FirstCookie = new Cookie("user", "This is the value of my first Cookie");
        //all pages on the server should receive the cookie
        FirstCookie.setPath("/");
        FirstCookie.setVersion(0);
        FirstCookie.setSecure(false);
        //60 sec * 60 min * 24h * 5d = 
        FirstCookie.setMaxAge(432000);
        FirstCookie.setComment("some comment");
        // save the cookies
        response.addCookie(FirstCookie);


    out.println("<html><body>");
    out.println("<h1>CookieServlet</h1>");
    out.println("<a href='ReadCookiesServlet'>To the Cookie page</a>");
    out.println("</body></html>");
    out.close();
}

第二个servlet:

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("Text/html");

    PrintWriter pw = response.getWriter();
    pw.println("<html><body>");
    pw.println("<h1>Bestaande cookies:</h1>");
    Cookie[] myCookies = request.getCookies();
    if (myCookies != null) {
        for (int i = 0; i < myCookies.length; i++) {
            pw.println("<table border=1 ALIGN=\'CENTER\'>");
            Cookie currentCookie = myCookies[i];
            if (currentCookie.getName().equalsIgnoreCase("user")) {

                pw.println("<tr><td>" + "Name : " + currentCookie.getName() + "<td></tr>");
                pw.println("<tr><td>" + "Path : " + currentCookie.getPath() + "<td></tr>");
                pw.println("<tr><td>" + "Version : " + currentCookie.getVersion() + "<td></tr>");
                pw.println("<tr><td>" + "Secure : " + currentCookie.getSecure() + "<td></tr>");
                pw.println("<tr><td>" + "Age : " + currentCookie.getMaxAge() + "<td></tr>");
                pw.println("<tr><td>" + "Value : " + currentCookie.getValue() + "<td></tr>");
                pw.println("<tr><td>" + "Comment : " + currentCookie.getComment() + "<td></tr>");
                pw.println("</table>");
            }
        }

    }

    pw.println("</body></html>");

    pw.close();
}

1 个答案:

答案 0 :(得分:1)

我怀疑它是空的,因为它没有被第一个servlet设置。它当前编写的方式,你必须提供这样的用户参数:FirstServletThatSetsCookie?user=flup当你浏览第一个servlet或它根本不会设置cookie!

请注意这一点:

String[] user = request.getParameterValues("user");
if (user != null) {
    // create new cookies