萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP Cookie 儲存中文完整實戰:編碼陷阱與最佳實踐

問題背景

Cookie 標準 (RFC 2109/2965/6265) 僅允許 ASCII 字元。直接存入中文會導致瀏覽器拒絕或伺服器解析錯誤。本文實測多種編碼方案,揭示常見誤區,給出生產可用的最佳實踐。

錯誤示範:直接存中文

<!-- addCookie.jsp -->
<%
    String name = request.getParameter("name"); // 例:"測試名字"
    Cookie c = new Cookie("username", name);    // 危險!非 ASCII
    c.setMaxAge(3600);
    response.addCookie(c);
%>
<!-- getCookie.jsp -->
<%
    Cookie[] cookies = request.getCookies();
    for (Cookie c : cookies) {
        if ("username".equals(c.getName())) {
            out.println(c.getValue()); // 亂碼或例外
        }
    }
%>

常見但有缺陷的方案

<!-- 僅 URLEncoder.encode,實測 Firefox 仍亂碼 -->
Cookie c = new Cookie("username", URLEncoder.encode(name, "UTF-8"));

原因:`request.getParameter()` 取得的字串已經歷過 Tomcat 解碼(預設 ISO-8859-1),若未正確還原,編碼前的位元組序列已錯誤。

經實測可靠的完整方案

寫入 Cookie (addCookie.jsp)

<%@ page pageEncoding="UTF-8" %>
<%
    // 1. 取得原始參數(Tomcat 預設以 ISO-8859-1 解碼 URL)
    String rawName = request.getParameter("name"); 
    
    // 2. 還原為正確的中文字串
    //    先按 ISO-8859-1 取回位元組,再用實際編碼(UTF-8/GBK)解碼
    byte[] bytes = rawName.getBytes("ISO-8859-1");
    String realName = new String(bytes, "UTF-8"); // 或 GBK,視前端編碼而定
    
    // 3. URLEncoder 編碼為 ASCII 安全字串
    String encoded = URLEncoder.encode(realName, "UTF-8");
    
    // 4. 寫入 Cookie
    Cookie c = new Cookie("username", encoded);
    c.setMaxAge(3600);
    c.setPath("/"); // 重要:指定路徑,否則預設為當前路徑
    response.addCookie(c);
%>

讀取 Cookie (getCookie.jsp)

<%@ page pageEncoding="UTF-8" %>
<%
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            if ("username".equals(c.getName())) {
                // URLDecoder 解碼還原中文
                String decoded = URLDecoder.decode(c.getValue(), "UTF-8");
                out.println("歡迎:" + decoded);
            }
        }
    }
%>

核心原理解析

瀏覽器發送請求
       ↓
URL 編碼 (UTF-8) → %E6%B8%AC%E8%A9%A6
       ↓
Tomcat 接收 → 預設用 ISO-8859-1 解碼 → 字串 "测试" 變成亂碼字元
       ↓
request.getParameter() 返回錯誤字串
       ↓
我們用 .getBytes("ISO-8859-1") 取回原始位元組
       ↓
new String(bytes, "UTF-8") 正確還原中文
       ↓
URLEncoder.encode(..., "UTF-8") → 安全存入 Cookie

生產環境強化建議

1. 統一使用 Filter 預處理編碼

@WebFilter("/*")
public class EncodingFilter implements Filter {
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
        req.setCharacterEncoding("UTF-8");
        res.setCharacterEncoding("UTF-8");
        chain.doFilter(req, res);
    }
}

配置後,`request.getParameter()` 直接返回正確中文,無需手動 `ISO-8859-1` 轉碼。

2. 封裝工具類

public class CookieUtil {
    public static void setCookie(HttpServletResponse resp, String name, String value, int maxAge) {
        try {
            String encoded = URLEncoder.encode(value, "UTF-8");
            Cookie c = new Cookie(name, encoded);
            c.setMaxAge(maxAge);
            c.setPath("/");
            c.setHttpOnly(true); // 防 XSS
            c.setSecure(true);   // 僅 HTTPS 傳輸(生產環境必開)
            resp.addCookie(c);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    public static String getCookie(HttpServletRequest req, String name) {
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (Cookie c : cookies) {
                if (name.equals(c.getName())) {
                    try {
                        return URLDecoder.decode(c.getValue(), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        return null;
                    }
                }
            }
        }
        return null;
    }
}

3. 考慮改用 Session / JWT

Cookie 容量限制 4KB、自動攜帶、CSRF 風險。敏感資料建議存 Server-side Session 或簽名 JWT,Cookie 僅存 Token。

總結

JSP 存中文 Cookie 必須經過 URLEncoder.encode(UTF-8),讀取用 URLDecoder.decode(UTF-8)。關鍵在於確保編碼前的字串已正確還原(配合 Filter 設定 UTF-8 最省心)。生產環境請務必加上 HttpOnly、Secure、SameSite 屬性,並評估是否應改用 Session/JWT 方案。

copyright © 萬盛學電腦網 all rights reserved