---
title: "Cookie"
author: "blaiu"
date: "2009-08-06T09:42:21Z"
tags: [".net", "JSP", "Web"]
categories: ["编程语言"]
slug: "cookie"
draft: false
lastmod: "2010-12-05T02:29:31Z"
id: 441294
url: "https://blaiu.iteye.com/blog/441294"
---

\[code="java"] public class Cookies { public int maxAge; // 设置该COOKIE的有效期,单位为秒 public String path; // cookie路径 Cookie\[] cookie\_get = {}; public Cookies() { // maxAge = -1; maxAge = 60\*60\*24\*14;//两周 // maxAge = 180;//两周 // path = "/"; } /\** * Put cookie to the client * * @param response * @param name * @param value \*/ public void putCookie(HttpServletResponse response, String name, String value) { try { Cookie cookie = new Cookie(name, encode(value)); cookie.setMaxAge(maxAge); cookie.setPath("/"); if(Common.isLinux()){ cookie.setDomain(".online.com"); } response.addCookie(cookie); } catch (Exception e) { e.printStackTrace(); } } /\** * get cookie from client * * @param request * @param name * @return \*/ public String getCookie(HttpServletRequest request, String name) { if (cookie\_get == null || cookie\_get.length == 0) { cookie\_get = request.getCookies(); } String returnStr; returnStr = null; try { for (int i = 0; cookie\_get != null && i &lt; cookie\_get.length; i++) { cookie\_get\[i].setPath(path); if (cookie\_get\[i].getName().equals(name)) { //cookie\_get\[i].setMaxAge(-1); returnStr = cookie\_get\[i].getValue().toString(); break; } } return decode(returnStr); } catch (Exception e) { return decode(returnStr); } } /\** * 清除Cookie * * @param response * HttpServletResponse * @param name * String \*/ public void removeCookie(HttpServletResponse response, String name) { putCookie(response, name, null); } /\** * 对给定字符进行 URL 解码 * * @param value * String * @return String \*/ private static String decode(String value) { String result = ""; if (!isEmpty(value)) { try { result = java.net.URLDecoder.decode(value, "UTF-8"); result = java.net.URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException ex) { } } return result; } /\** * 对给定字符进行 URL 编码 * * @param value * String * @return String \*/ private static String encode(String value) { String result = ""; if (!isEmpty(value)) { try { result = java.net.URLEncoder.encode(value, "UTF-8"); result = java.net.URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException ex) { } } return result; } /\** * 判断是否为空，为空返回true * * @param value * String * @return boolean \*/ private static boolean isEmpty(String value) { if (value == null || value.trim().equals("")) return true; else return false; } /\** * 查检二个数据是否为空，如果为空返回true * * @param value1 * @param value2 * @return \*/ public boolean isEmpty(String value1, String value2) { if (null == value1 || null == value2 || "".equals(value1) || "".equals(value2)) return true; else return false; } } LoginAction: 登录成功： Cookies cookies = new Cookies(); cookies.putCookie(response, "name", user.getName().toLowerCase().trim()); cookies.putCookie(response, "password",user.getPassWord()); js： 如果Cookie 从在自动登录 \[/code]