public String yzm() throws Exception {
response.setCharacterEncoding("UTF-8");
Object[] obj = verification.RandomCount();
OutputStream out = response.getOutputStream(); // 1. 獲取輸出流
ImageIO.write((BufferedImage) obj[1], "JPEG", out); // 2. 寫圖片
Cookie cookie = new Cookie("captcha", obj[0].toString()); // 3. 建 Cookie
cookie.setMaxAge(3600);
cookie.setPath("/");
response.addCookie(cookie); // 4. 添加 Cookie
out.flush();
return null;
}
現象:註釋掉 ImageIO.write 時 Cookie 正常;寫圖片後 Cookie 消失。
response.getOutputStream() 或 getWriter() 後,**響應體**已開啟。response.addCookie(),**頭部已發送,無法再添加**,Cookie 丟失。public String yzm() throws Exception {
response.setCharacterEncoding("UTF-8");
Object[] obj = verification.RandomCount();
// 1. 先處理所有 Header 相關操作
Cookie cookie = new Cookie("captcha", obj[0].toString());
cookie.setMaxAge(3600);
cookie.setPath("/");
response.addCookie(cookie); // 必須在 getOutputStream() 之前
// 2. 再獲取輸出流寫圖片
OutputStream out = response.getOutputStream();
ImageIO.write((BufferedImage) obj[1], "JPEG", out);
out.flush();
return null;
}