Adding A Cookie To A Response In Java

Here’s a basic example of how to set a cookie into a servlet response.

Cookie_name and cookie_value is the name and value for the cookie to store. The variable resp represents a javax.servlet.http.HttpServletResponse reference. Notice setMaxAge(int expiry) – this method sets how long the cookie should last before it expires in seconds. In this example I set a value of 2 weeks (multiplying the following together: 60 seconds, 60 minutes, 24 hours, 7 days, 2 weeks).

Cookie cookie = new Cookie(cookie_name, cookie_value);
cookie.setMaxAge(2 * 7 * 24 * 60 * 60);//Two weeks to expire, in seconds.
resp.addCookie(cookie);

Remember to add the import (the package includes the Cookie class and HttpServletResponse ):

import javax.servlet.http.*;