Improved Cookie management.

This commit is contained in:
Christian P. MOMON 2013-06-20 00:10:38 +02:00
parent 1e5127a009
commit 143b983f19

View file

@ -0,0 +1,176 @@
package fr.devinsy.kiss4web;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
*/
public class CookieHelper
{
static protected org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger (CookieHelper.class);
/**
*
*/
static public Cookie buildCookie (String name, String value, int duration, boolean isSecure)
{
Cookie result;
result = new Cookie (name, value);
result.setMaxAge (duration);
result.setPath ("/");
result.setSecure (isSecure);
//
return (result);
}
/**
*
*/
static public Cookie buildCookie (String name, String value, int duration)
{
Cookie result;
result = buildCookie(name, value, duration, false);
//
return (result);
}
/**
*
*/
static public Cookie getCookie (Cookie[] cookies, String key)
{
Cookie result = null;
if (cookies == null)
{
result = null;
}
else
{
boolean ended = false;
int cookieCounter = 0;
while (!ended)
{
if (cookieCounter < cookies.length)
{
if (key.equals (cookies[cookieCounter].getName ()))
{
ended = true;
result = cookies[cookieCounter];
}
else
{
cookieCounter += 1;
}
}
else
{
ended = true;
result = null;
}
}
}
//
return (result);
}
/**
*
*/
static public Cookie getCookie (HttpServletRequest request, String key)
{
Cookie result = null;
result = getCookie(request.getCookies (), key);
//
return(result);
}
/**
*
*/
static public Object getCookieValue (Cookie[] cookies, String key)
{
Object result;
Cookie cookie = getCookie(cookies, key);
if (cookie == null)
{
result = null;
}
else
{
result = cookie.getValue();
}
//
return(result);
}
/**
*
*/
static public Object getCookieValue (HttpServletRequest request, String key)
{
Object result;
result = getCookieValue (request.getCookies (), key);
//
return(result);
}
/**
*
*/
static public boolean exists(HttpServletRequest request, String key)
{
boolean result;
if (getCookieValue(request, key) == null)
{
result = false;
}
else
{
result = true;
}
//
return(result);
}
/**
*
*/
static public void set (HttpServletResponse response, String name, String value, int duration)
{
response.addCookie (buildCookie(name, value, duration));
}
/**
*
*/
static public void reset (HttpServletResponse response, String key)
{
response.addCookie(buildCookie(key, "", 0));
}
}