2015-12-25 46 views
0

我需要從servlet中刪除Cookie的幫助。無法從servlet中刪除cookie

我需要實現簡單的聊天程序:

在我檢查,如果輸入的是有效的(沒有空消息/用戶名和用戶名只能由數字或字母)的的doPost()函數

。 如果輸入有問題,我爲錯誤消息 創建新的Cookie並將其添加到響應中(我沒有設置Cookie的路徑或域)。

@Override 
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
     throws ServletException, IOException { 

    //--- Get Data From User --- 
    String userName= request.getParameter("userName"); 
    String msg= request.getParameter("comment"); 

    //--- Check if 'userName or 'msg' are empty --- 
    userName = userName.trim(); 
    msg = msg.trim(); 

    //--- Response --- 
    if (userName.isEmpty() || msg.isEmpty() || !userName.matches(pattern)) 
    { 
     if (userName.isEmpty() || msg.isEmpty()) 
     { 
      //store new Cookie for the error message 
      Cookie c1 = new Cookie("erorrEmpty", "\"<p>ERROR: \\\"username\\\" and \\\"message\\\" should not be empty.</p>\""); 
      // c1.setMaxAge(60*60); 
      //c1.setPath("."); 
      response.addCookie(c1); 
     } 
     if (!userName.matches("^[a-zA-Z0-9]+$")) 
     { 
      //store new Cookie for the error message 
      Cookie c2 = new Cookie("errorNotAlphanumeric", "\"<p>ERROR: \\\"username\\\" should consist of letters and numbers only.</p>\""); 
          // c2.setMaxAge(60*60); 
          // c2.setPath("."); 
      response.addCookie(c2); 
     } 

     //--- display form with errors --- 
     response.sendRedirect("/ex3/MsgServlet?action=1"); 

    } 
    else 
    { 
     // Insert New Message To The Vector.... 

     //--- display all messages --- 
     response.sendRedirect("/ex3/MsgServlet?action=2"); 
    } 
} 

在我檢查是否有餅乾的任何錯誤,並將其保存在一個字符串,我會在HTML輸出顯示的doGet()函數。 後,我救我嘗試刪除cookies(由MAXAGE(0)),但意外的是不工作的錯誤...

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

     PrintWriter out = null; 
    try{  

     //--- Determine Content Type --- 
     response.setContentType("text/html"); 

     //--- Get Writer --- 
     out = response.getWriter(); 


     if (request.getParameter("action").equals("1")) //display form with errors if exists 
     { 

      String error = ""; 

      //--- names of cookies to look for --- 
      String emptyFiledsCookieName = "erorrEmpty"; 
      String notAlphanumericCookieName = "errorNotAlphanumeric"; 

      Cookie[] cookies = request.getCookies(); 
      if (cookies != null) 
      { 
       for(Cookie cookie: cookies) 
       { 
        if (emptyFiledsCookieName.equals(cookie.getName()) || notAlphanumericCookieName.equals(cookie.getName())) 
        { 
         error=error+ cookie.getValue() +"\n"; 
        } 
       } 

       for(Cookie cookie: cookies) 
       { 
        if (emptyFiledsCookieName.equals(cookie.getName()) || notAlphanumericCookieName.equals(cookie.getName())) 
        { 
         cookie.setMaxAge(0); 
        } 
       } 
      } 


       out.println("<html><head><title>"); 
       out.println("compose message</title>"); 
       out.println("<meta charset=\"UTF-8\">"); 
       out.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">"); 
       out.println("</head><body>"); 

       //--- Print Errors --- 
       out.println(error); 

       out.println("<form action=\"MsgServlet\" method=\"POST\" id=\"usrform\">"); 
       out.println("<p>username:</p>"); 
       out.println("<input type=text name=userName><br>"); 
       out.println("<input type=submit value=\"post\"></form>"); 
       out.println("<br><p>message:</p><textarea rows=\"4\" cols=\"50\" name=\"comment\" form=\"usrform\"></textarea>"); 
       out.println("</body></html>"); 

      } 
     else if (request.getParameter("action").equals("2")) 
     { 
      //display messages 

     } 
} 

我看到其他的問題在這個問題上,但他們提到setDomain()和setPath()函數。這與我無關,因爲我沒有在創建Cookie時使用它們。

回答

0

如果你能得到它,你可以改變它!

你必須將其添加到答案。

HttpServletResponse resp 

Cookie[] cookies = request.getCookies();  

Cookie the_cookie // get the good one ! 

the_cookie.setMaxAge(0); 

resp.addCookie(the_cookie); 

或看到:How do you remove a Cookie in a Java Servlet

+0

謝謝!!!!!你救了我。這行「resp.addCookie(the_cookie);」失蹤。 – daniel

0

getMaxAge(INT):

  • 獲取此cookie秒的最長期限。
  • 默認情況下,返回-1,表示cookie將一直存在,直到瀏覽器關閉。
  • 如果爲負數,則意味着cookie會一直存在,直到瀏覽器關閉。

    public static Cookie eraseCookie(String CookieName, String Path) { 
    Cookie cookie = new Cookie(CookieName, ""); 
    cookie.setMaxAge(0);// Set as a o 
    cookie.setPath(Path); 
    return cookie; 
    } 
    

    樂意幫助