package com.jt.util;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 該工具API主要的任務
* 1.根據cookie的名稱 傳回cookie對象
* 2.根據cookie的名稱 傳回valve的值
* 3.新增cookie方法
* 4.删除cookie方法
*/
public class CookieUtil {
/**
*
* @param cookieName 需要比對的cookie名
* @param request request對象
* @return 傳回一個cookie對象
*/
public static Cookie getCookie(String cookieName, HttpServletRequest request){
Cookie[] cookies = request.getCookies();
if(cookies !=null && cookies.length >0) {
for (Cookie cookie : cookies) {
if (cookieName.equals(cookie.getName())) {
return cookie;
}
}
}
return null ;
}
/**
*
* @param cookieName 需要比對的cookie名
* @param request request對象
* @return 傳回cookie的值
*/
public static String getCookieValue(String cookieName,HttpServletRequest request){
Cookie cookie = getCookie(cookieName, request);
return cookie ==null?null:cookie.getValue();
}
/**
*
* @param cookieName 需要比對的cookie名
* @param cookieValue 設定的cookie值
* @param path 設定路徑下的能通路cookie
* @param domain 設定作用域名能通路到cookie
* @param maxAge 設定存活時間
* @param response 響應資訊
*/
public static void addCookie(String cookieName, String cookieValue, String path,
String domain, int maxAge, HttpServletResponse response){
Cookie cookie = new Cookie(cookieName,cookieValue);
cookie.setPath(path);
cookie.setDomain(domain);
cookie.setMaxAge(maxAge);
response.addCookie(cookie);
}
/**
*
* @param cookieName 需要比對的cookie名
* @param path
* @param domain
* @param response
*/
public static void deleteCookie(String cookieName,String path,
String domain,HttpServletResponse response){
addCookie(cookieName,"",path, domain, 0, response);
}
}