[JAVA] Create/Delete/Check Java Cookies
// Create a cookie
public void setCookie(HttpServletResponse res,String value){
Cookie cookie = new Cookie("Cookies I want to create ID", value); //
Create a cookie by naming it( key, value )
cookie.setMaxAge(60*60*24); // Cookie expiration date: set to one day(60seconds * 60minute * 24
hour)
cookie.setPath("/"); // Make it accessible from all paths
res.addCookie(cookie); //response에 Cookie add
}
// Get Cookies
public String getCookie(HttpServletRequest req){
Cookie[] cookies=req.getCookies(); // Get all cookies
if(cookies!=null){
for (Cookie c : cookies) {
String name = c.getName(); // Get cookie name
String value = c.getValue(); // Get cookie value
if (name.equals("Cookies I'm Looking For ID")) {
return value;
}
}
}
return null;
}
// Remove specific cookies
public void deleteCookie(HttpServletResponse res){
Cookie cookie = new Cookie("Cookies you want to delete ID", null); // Set the value for the cookie to be deleted to null
cookie.setMaxAge(0); // Set the valid time to 0 to expire immediately.
res.addCookie(cookie); // Add to response to make it go away
}
// remove all cookies
public void deleteAllCookies(HttpServletRequest req,HttpServletResponse res) {
Cookie[] cookies = req.getCookies(); // Store information of all cookies in cookies
if (cookies != null) { // Execute if there is at least one cookie
for (int i = 0; i < cookies.length; i++) {
cookies[i].setMaxAge(0); // set valid time to 0
res.addCookie(cookies[i]); // Add to response to expire.
}
}
}
😀
Thank you!!
Comments
Post a Comment