import java.io.UnsupportedEncodingException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Administrator
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class Cookies {
public int maxAge; // 设置该COOKIE的有效期,单位为秒
public String path; // cookie路径
Cookie[] cookie_get = {};
public Cookies() {
maxAge = -1;
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(path);
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 < 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, "GBK");
} 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, "GBK");
} 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;
}
}
java读写Cookie
最新推荐文章于 2024-10-02 22:02:29 发布