Sessions should be managed with some care, for two main reasons :
- sessions have various security risks associated with them.
- sessions consume server resources, and should likely be avoided if possible.
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, for the reasons stated above, the creation and destruction of sessions should likely be more tightly controlled by the application.
Here is 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
- 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)