The Servlet API is, unfortunately, rather liberal in creating sessions. Various tools have default behaviors which can implicitly create sessions in the background. It's very easy for an application to "accidentally" create a session, even when one was not explicitly requested.
An an example, JSPs will often create a session if one doesn't already exist. This allows JSPs to use the implicit session variable. As a second example, the request.getSession() method will also automatically create a session if one doesn't already exist.
However, sessions should be managed with some care, for two main reasons:
- sessions have various security risks associated with them.
- sessions consume server resources.
So, the creation and destruction of sessions should likely be tightly controlled by the application.
Here's an example of a reasonable set of policies regarding sessions:
- use a <%@ page session="false" %> directive at the top of every JSP that doesn't use a session
- consider disabling URL rewriting altogether
- create a new session only when the user logs in (and not before)
- when the user logs out, invalidate the session and delete any related cookie
- in web.xml, ensure session time out is set to value which isn't unnecessarily long
- defend against Cross-Site Request Forgery attacks (which hijack existing sessions)
Always maintain HttpSessions
Beware of custom cookies
Beware of common hacks
Beware of URL rewriting