獲取cookie的3種方式

QLearnFun發表於2017-03-22

建立Cookie

//使用URLEncoder.encode()編碼,因為cookie不能儲存中文,否則有中文會報錯
String city = URLEncoder.encode("北京_BJ", "utf-8");
//建立Cookie
Cookie cookie = new Cookie("city", city);
//設定Cookie的最大生命週期,否則瀏覽器關閉後Cookie即失效
cookie.setMaxAge(Integer.MAX_VALUE);
//將Cookie加到response中
response.addCookie(cookie);

獲取Cookie的3種方式:

JSP表示式

在jsp頁面中遍歷cookie,找到指定的cookie

<%
    String city = "";
    //獲取所有Cookie
    Cookie[] cookies = request.getCookies();
    //如果瀏覽器中存在Cookie
    if (cookies != null && cookies.length > 0) {
        //遍歷所有Cookie
        for(Cookie cookie: cookies) {
            //找到name為city的Cookie
            if (cookie.getName().equals("city")) {
                //使用URLDecode.decode()解碼,防止中文亂碼
                city = URLDecoder.decode(cookie.getValue(), "utf-8");
            }
        }
    }
%>

在需要顯示的位置用jsp表示式展示

<%= city %>

EL內建物件cookie

使用 ${cookie.city.value } 直接獲得即可,但如果有中文的話,會出現中文亂碼

${cookie.city.value }

使用jQuery,需引入js檔案:
jquery-3.2.0.jsjquery-3.2.0.min.js 官網下載連結

<script src="js/jquery-3.2.0.js"></script>

使用jQuery Cookie外掛,需引入js檔案: jquery.cookie.js 官網下載連結

<script src="js/jquery.cookie.js"></script>

將Cookie存的內容放到id=”city”的元素中

<script type="text/javascript">
$(document).ready(function() {
    //$.cookie("city") 獲取name為city的Cookie的值
    //$("#city").val(str) 設定id="city"的元素的值為str
    $("#city").val($.cookie("city"));
});
</script>
<input type="text" id="city">

測試結果

測試結果

測試程式碼

testCookie.jsp

<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>testCookie</title>
<script src="js/jquery-3.2.0.js"></script>
<script src="js/jquery.cookie.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    //$.cookie("city") 獲取name為city的Cookie的值
    //$("#city").val(str) 設定id="city"的元素的值為str
    $("#city").val($.cookie("city"));
});
</script>
<style type="text/css">
    input {
        width:200px;
    }
</style>
</head>
<body>
<%
    String city = "";
    //獲取所有Cookie
    Cookie[] cookies = request.getCookies();
    //如果瀏覽器中存在Cookie
    if (cookies != null && cookies.length > 0) {
        //遍歷所有Cookie
        for(Cookie cookie: cookies) {
            //找到name為city的Cookie
            if (cookie.getName().equals("city")) {
                //使用URLDecode.decode()解碼,防止中文亂碼
                city = URLDecoder.decode(cookie.getValue(), "utf-8");
            }
        }
    }
%>
<form action="TestCookieServlet">
1.JSP表示式:<br>
&nbsp;&nbsp;&nbsp;<input type="text" value="<%=city %>" ><br><br>
2.EL語句:<br>
&nbsp;&nbsp;&nbsp;<input type="text" value="${cookie.city.value }"><br><br>
3.jQuery:<br>
&nbsp;&nbsp;&nbsp;<input type="text" id="city"><br><br>
&nbsp;&nbsp;&nbsp;<input type="submit" value="獲取Cookie" ><br>
</form>
</body>
</html>

TestCookieServlet.java

package com.cookie.test;

import java.io.IOException;
import java.net.URLEncoder;

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;

@WebServlet("/TestCookieServlet")
public class TestCookieServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

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

        //使用URLEncoder.encode()編碼,因為cookie不能儲存中文,否則有中文會報錯
        String city = URLEncoder.encode("北京_BJ", "utf-8");
        //建立Cookie
        Cookie cookie = new Cookie("city", city);
        //設定Cookie的最大生命週期,否則瀏覽器關閉後Cookie即失效
        cookie.setMaxAge(Integer.MAX_VALUE);
        //將Cookie加到response中
        response.addCookie(cookie);
        //重定向到jsp頁面
        response.sendRedirect("testCookie.jsp");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}

相關文章