How can I set a cookie in JSP?-

response. setHeader(”Set-Cookie”, “cookie string”); To give the response-object to a bean, write a method setResponse (HttpServletResponse response) – to the bean, and in jsp-file:<% bean. setResponse (response); %>

To set a cookie in JSP (JavaServer Pages), you can use the following syntax and code:

jsp

<%@ page import="javax.servlet.http.Cookie" %>

<%
Cookie myCookie = new Cookie(“cookieName”, “cookieValue”);
myCookie.setMaxAge(3600); // Set the cookie’s maximum age in seconds, here it is set to 1 hour (3600 seconds)
response.addCookie(myCookie);
%>

In this example:

  1. <%@ page import="javax.servlet.http.Cookie" %> imports the Cookie class from the javax.servlet.http package.
  2. Cookie myCookie = new Cookie("cookieName", "cookieValue"); creates a new Cookie object with a name (“cookieName”) and a value (“cookieValue”).
  3. myCookie.setMaxAge(3600); sets the maximum age of the cookie in seconds. In this case, it’s set to 1 hour (3600 seconds). You can adjust this value according to your requirements.
  4. response.addCookie(myCookie); adds the cookie to the response, which will be sent to the client’s browser.

Make sure to include this code within your JSP file where you want to set the cookie.