Cookie mycook = new Cookie(“name”,”value”);
response.addCookie(mycook);
Cookie killmycook = new Cookie(“mycook”,”value”);
killmycook.setMaxAge(0);
killmycook.setPath(“/”);
killmycook.addCookie(killmycook);
In Advanced Java, particularly within a JavaServer Pages (JSP) page, you can set and delete cookies using the following methods:
- Setting a Cookie: To set a cookie in a JSP page, you can use the following syntax:
jsp
<%
// Set a cookie named "myCookie" with a value of "cookieValue"
Cookie myCookie = new Cookie("myCookie", "cookieValue");
// Set the maximum age of the cookie in seconds (e.g., 1 day)
myCookie.setMaxAge(24 * 60 * 60);
// Add the cookie to the response
response.addCookie(myCookie);
%>
This code creates a new
Cookie
object, sets its name and value, and then adds it to the response. - Deleting a Cookie: To delete a cookie, you can set its maximum age to 0. This effectively makes the cookie expire immediately. Here’s an example:
jsp
<%
// Create a cookie with the same name as the one you want to delete
Cookie deleteCookie = new Cookie("myCookie", "");
// Set the maximum age to 0 to delete the cookie
deleteCookie.setMaxAge(0);
// Add the cookie to the response
response.addCookie(deleteCookie);
%>
This code creates a new
Cookie
object with the same name as the cookie you want to delete, sets its maximum age to 0, and then adds it to the response.
Remember that setting and deleting cookies should be done before any content is sent to the client, as cookies are part of the HTTP header, and headers must be sent before the response body.