Cookies are text data sent by server to the client to mantain information. The data sent gets saved at the client local machine. When client send request to server, it passes the cookies stored by the server in request header as in the following example:
Set-Cookie: LSID=HYEGYUGe…Eaem_vYg; Domain=mastertheboss.com; Path=/application; Expires=Wed, 11-Mar-2014 21:21:01 GMT; Secure; HttpOnly
Servlet API provides cookies support through javax.servlet.http.Cookie class that implements Serializable and Cloneable interfaces.
Setting Cookies
In the following example we will show how to set some information using a Cookie in a Servlet and later retrieve this information from another Servlet.
@WebServlet(name = "CookieServlet", urlPatterns = {"/CookieServlet"}) public class SetCookieServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); Cookie cookie = new Cookie("userId","ABX123456"); cookie.setHttpOnly(true); cookie.setMaxAge(-30); response.addCookie(cookie); try { out.println("Cookie Set by Servlet!"); } finally { out.close(); } } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
As you can see, in order to create a Cookie you can use the constructor of javax.servlet.http.Cookie object passing both the name and value or it can be done by passing values to the cookie’s setName and setValue methods. Once done, the cookie’s setMaxAge and setHttpOnly methods are called, setting the time of life for the cookie and ensuring that it will be
guarded against client-side scripting. In the end, the cookie is placed into the response by passing it to the response object’s addCookie method.
Reading Cookies
Cookies can be retrieved by any class which has access to HTTP’s request object, via the getCookies method:
Cookie[] cookies = request.getCookies();
The cookie object array can be then iterated over in order to obtain each cookie and print out its contents. Here’s how to do it:
for(Cookie cookie:cookies){ out.println("<p>"); out.println("Cookie Name: " + cookie.getName()); out.println("<br/>"); out.println("Value: " + cookie.getValue()); out.println("</p>"); }