JAVA : Cookies Manipulation (ADD / UPDATE / DELETE)
ADD / EDIT Cookie in Java :
Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management.A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets.
The servlet sends cookies to the browser by using the
HttpServletResponse.addCookie(javax.servlet.http.Cookie)
method, which adds fields to HTTP response headers to send cookies to the browser, one at a time. The browser is expected to support 20 cookies for each Web server, 300 cookies total, and may limit cookie size to 4 KB each.public static void insertOrUpdateCookie(HttpServletRequest httpReq,
HttpServletResponse httpRes, String name, String value) throws Exception {
Cookie[] cookies = httpReq.getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
String cookieName = cookie.getName();
if (name.equalsIgnoreCase(cookieName)) {
if(LOGGER.isLoggable(Level.FINE)){
LOGGER.fine("prev value : " +cookie.getValue()+" Curvalue >> "+value);
}
cookie.setValue(value);
cookie.setSecure(true); //For HTTPS only
cookie.setDomain("ktpot.com"); // Explicitly Setting domain name
cookie.setMaxAge(30 * 60);// 30 mins
cookie.setPath("/");
httpRes.addCookie(cookie);
// httpRes.flushBuffer();
return;
}
}
Cookie addCookie = new Cookie(name, value);
cookie.setSecure(true); //For HTTPS only
cookie.setDomain("ktpot.com"); // Explicitly Setting domain name
addCookie.setMaxAge(30 * 60);// 30 mins
addCookie.setPath("/");
httpRes.addCookie(addCookie);
return;
}
}
public static void deleteCookie(HttpServletRequest httpReq,
HttpServletResponse httpRes, String name) {
Cookie[] cookies = httpReq.getCookies();
if(cookies == null || cookies.length == 0)
{
return;
}
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
String cookieName = cookie.getName();
if (name.equalsIgnoreCase(cookieName)) {
cookie.setMaxAge(0);
cookie.setValue(null);
cookie.setSecure(true); //For HTTPS only
cookie.setDomain("ktpot.com"); // Explicitly Setting domain name
cookie.setPath("/");
httpRes.addCookie(cookie);
return;
}
}
}
public static String getCookie(HttpServletRequest httpReq,
HttpServletResponse httpRes, String name) {
String cookieValue = null;
Cookie[] cookies = httpReq.getCookies();
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
String cookieName = cookie.getName();
if (name.equalsIgnoreCase(cookieName)) {
cookieValue = cookie.getValue();
}
}
return cookieValue;
}
0 comments:
Post a Comment