To overcome the statelessness of HTTP protocol, Servlet specifications defines three mechanisms of session tracking:
Cookies In the start of a session, the Servlet container sends a cookie in response to the client's first request. This cookies contains session information (JSESSIONID). Each subsequent request from the client sends the same cookies, hence associating multiple requests to a single session.
SSL sessions HTTPS protocol has a built-in mechanism (SSL: Secure Sockets Layer) allowing multiple requests from a client to be identified as being part of a session. A servlet container takes advantage of SSL to track the session.
-
URL rewriting URL rewriting is the last option we should resort to for session tracking. When a client browser does not accept a cookie, URL rewriting may be used by the container for session tracking. In this mechanism each hyperlink generated by the servlet container appends a session ID (that is a developer's responsibility unless he uses some high level framework like JSF), to the URL path. The example url looks like this: http://www.example.com/myPage.html;jessionid=232342342 URL rewriting exposes session ID at many undesirable places, for example in browser's address bar, logs, bookmarks etc. URL rewriting should not be used as a session tracking mechanism if we don't have other options supported.
How to specify the session tracking mode?
Starting Servlet 3, ServletContext introduces a new method:
void setSessionTrackingModes (Set<SessionTrackingMode> sessionTrackingModes);
The enum SessionTrackingMode has following modes:
We can set the intended session tracking modes via ServletContextListener:
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.SessionTrackingMode;
import javax.servlet.annotation.WebListener;
import java.util.EnumSet;
@WebListener
public class SessionTrackingModeSetter implements ServletContextListener {
@Override
public void contextInitialized (ServletContextEvent event) {
event.getServletContext()
.setSessionTrackingModes(EnumSet.of(SessionTrackingMode.URL));
}
@Override
public void contextDestroyed (ServletContextEvent sce) {
}
}
Alternatively we can set the mode in web.xml:
<web-app>
<session-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
</web-app>
We can use multiple tracking-mode elements within a single session-config element in the web.xml.
Example Project
This example demonstrates the session tracking mode 'URL'. Note that we have to append session id with hyperlink ourselves. The framework like JSF generates those kind of session appended URL implicitly. Dependencies and Technologies Used: - Java Servlet API 3.0.1
- JDK 1.8
- Maven 3.3.9
|