我是 servlet 的新手,我有一个关于 cookie 的问题。
我有一个 servlet,我在其中创建了一个 cookie,并编写了一个页面,我在其中放置了指向另一个要检索 cookie 的 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();
}
第二个小服务程序:
/**
* @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();
}