Sessions and Cookies

In the previous tutorials we’ve been creating and setting sessions. In this tutorial we’ll take a close look at sessions, and how to delete them. We’ll also cover cookies in this tutorial.

session is an object that keeps user data. The session runs on the server.
cookie is an object that keeps user data. The cookie runs on the client pc.

In this tutorial we’ll look at unsetting sessions and creating cookies .

So why would we wanna unset sessions? The answer is easy: sessions eat memory and the less memory we use the better.

If we want every session to stop after a certain amount of time we can use the web.xml file.

<web-app ...>
  <session-config>
    <session-timeout>25</session-timeout>
  </session-config>>
</web-app>

In this case every session will unset itself after 25 minutes.

Sometimes we just want one session to stop after a certain amount of time. For example a user that can only visit the site for 15 minutes.

session.setMaxInactiveInterval(15*60);

The argument is seconds, not minutes. 15 * 60 seconds = 15 minutes.

Sometimes we want to stop a session at once, for example when the user signs out. That’s when we use invalidate (it’s also possible to use setMaxInactiveInterval(0) but that looks weird).

// user wants to log out
session.invalidate();

Now the user can’t use the session data anymore.

Sometimes we want to keep user data longs than 1 session, for example we want to keep the user signed in for two weeks. That’s when cookies come in play! The cookie data is stored on the client pc so we don’t have to worry about excessive memory use.

Cookie cookie = new Cookie(“username”, “john”);

cookie.setMaxAge("14*24*60*60"); // two weeks
response.addCookie(cookie);

The cookie is now saved on the client pc for two weeks.

To check out all the cookies from one application use the following code:

Cookie[] cookies = request.getCookies();
foreach(Cookie c : cookies) {
  out.println("Cookie: " + c.getValue());
}

This concludes the tutorial about sessions and cookies.