关于Servlet中的cookie的查询

时间:2014-05-31 03:22:20

标签: servlets

我尝试在响应中添加两个cookie,然后使用方法长度返回cookie的数量。我发现它返回3个cookie,即使我删除所有cookie,它仍然会返回1.我不明白为什么在运行时生成更多cookie。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    {
//      Account_info AI = new Account_info(request.getParameter("id"), request.getParameter("pass"));
//      
//      String check = AI.check();
//      
//      request.setAttribute("info", check);
//      RequestDispatcher view = request.getRequestDispatcher("Form.jsp");
//      view.forward(request, response);

        Cookie[] c = request.getCookies();

        if(c == null)
        {
            String name = request.getParameter("id");
            String passw = request.getParameter("pass");
            if(name.equals("nmc") && passw.equals("nmc"))
            {
                Cookie usercc = new Cookie("id", name);
                Cookie passcc = new Cookie("pass", passw);
                usercc.setMaxAge(0);
                passcc.setMaxAge(0);
                response.addCookie(passcc);
                response.addCookie(usercc);
                response.sendRedirect("Form.jsp");
            }
            else
            {
                response.sendRedirect("Login.html");
            }
        }
        else if(c != null)
        {
            System.out.println("have "+c.length+" cookie");
            String userName = "";
            String passWord = "";
            for(Cookie cookie : c)
            {
                cookie.setMaxAge(0);
                if(cookie.getName().equals("id"))
                {
                    System.out.println(cookie.getMaxAge());
                    userName = cookie.getValue();
                    System.out.println(userName+" id");
                }
                if(cookie.getName().equals("pass"))
                {
                    passWord = cookie.getValue();
                    System.out.println(passWord+" pass");
                }
            }

            if(userName.equals("nmc") && passWord.equals("nmc"))
            {
                response.sendRedirect("Form.jsp");
        //      view.forward(request, response);
            }
            else
            {
                response.sendRedirect("Login.html");
    //          view.forward(request, response);
            }
        }
    }

0 个答案:

没有答案