create cookie:
Cookie userCookie = new Cookie("user", "uid1234");
userCookie.setMaxAge(60*60*24*365); // Store cookie for 1 year
response.addCookie(userCookie);
read cookie:
/** Given the request object, a name, and a default value,
* this method tries to find the value of the cookie with
* the given name. If no cookie matches the name,
* the default value is returned.
*/
public static String getCookieValue
(HttpServletRequest request,
String cookieName,
String defaultValue) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for(int i=0; i<cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
return(cookie.getValue());
}
}
}
return(defaultValue);
}
Cookie userCookie = new Cookie("user", "uid1234");
userCookie.setMaxAge(60*60*24*365); // Store cookie for 1 year
response.addCookie(userCookie);
read cookie:
/** Given the request object, a name, and a default value,
* this method tries to find the value of the cookie with
* the given name. If no cookie matches the name,
* the default value is returned.
*/
public static String getCookieValue
(HttpServletRequest request,
String cookieName,
String defaultValue) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for(int i=0; i<cookies.length; i++) {
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName())) {
return(cookie.getValue());
}
}
}
return(defaultValue);
}
Comments
Post a Comment