servlet之cookie

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

/**
 * Created by leo on 17-7-14.
 */
/*
Cookie 是存儲在客戶端計算機上的文本文件,並保留了各種跟蹤信息。Java Servlet 顯然支持 HTTP Cookie。
識別返回用戶包括三個步驟:
服務器腳本向瀏覽器發送一組 Cookie。例如:姓名、年齡或識別號碼等。
瀏覽器將這些信息存儲在本地計算機上,以備將來使用。
當下一次瀏覽器向 Web 服務器發送任何請求時,瀏覽器會把這些 Cookie 信息發送到服務器,服務器將使用這些信息來識別用戶。

Servlet Cookie 處理需要對中文進行編碼與解碼,方法如下:
String   str   =   java.net.URLEncoder.encode("中文","UTF-8");            //編碼
String   str   =   java.net.URLDecoder.decode("編碼後的字符串","UTF-8");   // 解碼
 */
@WebServlet("/CookieServlet")
public class CookieServlet extends HttpServlet {


    private static final long serialVersionUID = 9072647170248270425L;

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        Cookie name = new Cookie("name", URLEncoder.encode(request.getParameter("name"), "UTF-8"));
        Cookie password = new Cookie("psssword", URLEncoder.encode(request.getParameter("password"), "UTF-8"));
        String printNmae = URLEncoder.encode(request.getParameter("name"), "UTF-8");
        System.out.println(printNmae);

        name.setMaxAge(60 * 5);
        password.setMaxAge(60 * 5);
        response.addCookie(name);
        response.addCookie(password);

        PrintWriter out = response.getWriter();
        out.println("set two cookies. name = " + name + ",password = " + password + "printName = " + printNmae);
    }
}
/*
序號	方法 & 描述
1	public void setDomain(String pattern)
該方法設置 cookie 適用的域,例如 w3cschool.cc。
2	public String getDomain()
該方法獲取 cookie 適用的域,例如 w3cschool.cc。
3	public void setMaxAge(int expiry)
該方法設置 cookie 過期的時間(以秒爲單位)。如果不這樣設置,cookie 只會在當前 session 會話中持續有效。
4	public int getMaxAge()
該方法返回 cookie 的最大生存週期(以秒爲單位),默認情況下,-1 表示 cookie 將持續下去,直到瀏覽器關閉。
5	public String getName()
該方法返回 cookie 的名稱。名稱在創建後不能改變。
6	public void setValue(String newValue)
該方法設置與 cookie 關聯的值。
7	public String getValue()
該方法獲取與 cookie 關聯的值。
8	public void setPath(String uri)
該方法設置 cookie 適用的路徑。如果您不指定路徑,與當前頁面相同目錄下的(包括子目錄下的)所有 URL 都會返回 cookie。
9	public String getPath()
該方法獲取 cookie 適用的路徑。
10	public void setSecure(boolean flag)
該方法設置布爾值,表示 cookie 是否應該只在加密的(即 SSL)連接上發送。
11	public void setComment(String purpose)
設置cookie的註釋。該註釋在瀏覽器向用戶呈現 cookie 時非常有用。
12	public String getComment()
獲取 cookie 的註釋,如果 cookie 沒有註釋則返回 null。
 */

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章