簡體   English   中英

如何使用jsp在flex中維護最后一個cookie值?

[英]How can i maintain last cookie value in flex with jsp?

我登錄時在flex中的登錄表單中,我已經在jsp中創建了一個像這樣的cookie: setValueCookie.jsp

<%@ page language="java" import="java.util.* , javax.net.*" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<%
    String username = request.getParameter("value");
    System.out.println("Email got in cookieSet = " + username);

    if(username==null) username="";

    Date now = new Date();
    String timestamp = now.toString();
    Cookie cookie = new Cookie("username",username);
    cookie.setMaxAge(365 * 24 * 60 * 60);
    response.addCookie(cookie);

%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>DashBoard-Cookie</title>
</head>
<body>

</body>
</html>

現在使用Http服務請求參數,我正在將用戶名“值”傳遞給此jsp。 我正在這樣從getValueCookie.jsp中讀取cookie值

<%
 String cookieName = "username";
 Cookie cookies [] = request.getCookies ();
 Cookie myCookie = null;
 String result; 
 if (cookies != null)
 {
 for (int i = 0; i < cookies.length; i++) 
 {
    if (cookies [i].getName().equals (cookieName))
    {
    myCookie = cookies[i];
    break;
    }
 }
}

%>
<data>
  <status><%=myCookie.getValue().toString()%></status>
</data>

通過我獲得的httpservice值,但是如果我打開一個新窗口或任何新的選項卡cookie值都沒有得到,我該如何解決呢? 提前致謝。

即使發布的代碼非常繁瑣和討厭(第二個示例可以通過EL中的${cookie.username.value}來完成,而scriptlet也不可以,但這應該直接在HttpServletFilter ),代碼看起來合法。

有兩點可能引起人們注意:

  1. Cookies綁定到當前請求協議,域和(默認情況下)上下文路徑。 因此,如果您通過它們中的任何一個進行切換,則該cookie將在另一個請求中不可訪問。

  2. 在JSP文件要求IllegalStateException: Response already committed一半時,修改響應標頭(需要在響應標頭中設置cookie)。 檢查服務器日志。 如果它們在那里,則只需將scriptlet移至JSP頁面的頂部或-preferably-,只需輕輕地使用HttpServletFilter 對於這種邏輯,JSP是錯誤的地方。

就是說,您考慮過使用HttpSession嗎? 它提供了相同的功能,但是因為您不必為松散的cookie煩惱而容易得多,而且問題也更少。 通過request.getSession()獲取會話,並使用session.setAttribute(key, value)將對象存儲在會話中,並使用session.getAttribute(key)從會話中檢索對象。 該會話用於此,它又由cookie支持,但是您無需自己進行管理。 服務器將透明地為您完成此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM