XML technologies / XSLT / Java and XSLT / Further techniques / Session tracking without cookies
(Excerpt from “Java und XSLT” by Eric M. Burke)
Session tracking is essential in many web applications. HTTP is inherently connectionless: the browser establishes a new connection to the web server whenever the user follows a hyperlink or submits a form. After the request and response, the connection between browser and server is closed again.
This poses a problem for servlet authors. Although browser and server maintain no persistent connection between page requests, the application must retain state information for each user. This enables applications such as shopping carts. With every browser request, the servlet must determine the user’s identity and session information.
The servlet API for session tracking
The traditional approach to session tracking in a servlet uses the interface javax.servlet.http.HttpSession. It lets a web application store information about a user across multiple requests. It uses attributes, each with a name and a value. This code is part of a servlet that uses HttpSession:
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// hole eine Instanz von HttpSession für diesen Nutzer. Der Parameter "true"
// besagt, daß das Objekt erzeugt werden soll, falls es nicht existiert.
HttpSession session = req.getSession(true);
// hole den Warenkorb dieses Nutzers
Cart cart = (Cart) session.getAttribute("shoppingCart");
if (cart == null) {
cart = new Cart( );
session.setAttribute("shoppingCart", cart);
}
...
}The first line of method doGet( ) locates the instance of HttpSession associated with the user. Parameter true causes a new session to be created if none exists. Method getAttribute( ) on HttpSession can now retrieve an object of type Cart.
Figure: Session tracking
The HttpSession normally uses browser cookies. A cookie is a randomly generated sequence of characters stored on the client that uniquely identifies a user. When the browser requests the servlet, it looks for a cookie named jsessionid and uses its value to find the corresponding instance of HttpSession. The figure above illustrates this model of session tracking.
Cookies also have drawbacks. They simplify session tracking but raise privacy concerns among users who do not want their browsing habits monitored. Many users therefore disable cookies. In that case, servlets must use another tracking technique.
The standard servlet API offers another mechanism when cookies are disabled: URL rewriting, which appends the session identifier to the URL. Whenever a user follows a hyperlink or submits an XHTML form, the identifier accompanies the request. This requires some programming, however. Imagine a servlet returning an XHTML page containing:
Hier klicken, um weiterzugehen:
<a href="/shopping/moveNext"/>weiter</a>Session tracking cannot work here because following the hyperlink loses the session identifier. The HTML should look like this:
Hier klicken, um weiterzugehen:
<a href="/shopping/moveNext;jsessionid=0e394s8a576f67b38s7"/>weiter</a>Now, following the link sends the session identifier (jsessionid) to the servlet as part of the URL.
The value of jsessionid must not be hardcoded. It must be generated dynamically for each instance of HttpSession to make it harder for attackers to obtain session identifiers and impersonate users. (Sessions and identifiers typically expire after 30 minutes of inactivity and must then be regenerated.) The XHTML therefore cannot be static: each link and form action needs its dynamically inserted session identifier. HttpServletResponse provides method encodeURL( ) for this purpose:
String originalURL = "/shopping/moveNext";
String encodedURL = response.encodeURL(originalURL);URL encodedURL now includes the session ID if cookie jsessionid was not found. This technique must be applied to every hyperlink and form action on the website for session tracking to work.
Session tracking with Java and XSLT
With XSLT, session tracking is slightly more complicated because the stylesheet generates the URL instead of the servlet. It might contain:
<xsl:template match="cart">Weiter <a href="/shopping/moveNext"/>weiter</a> ...</xsl:template>As explained, the jsessionid must be appended to the URL. Follow these steps:
Determine in the servlet whether cookies are enabled.
If disabled, determine the value of
jsessionid.Pass string
;jsessionid=XXXXto the XSLT stylesheet as a parameter, whereXXXXrepresents the session identifier.The stylesheet appends the session-ID parameter to every hyperlink and form-action URL.
When cookies are enabled, manual session tracking is unnecessary. Method isRequestedSessionIdFromCookie( ) from interface javax.servlet.http.HttpServletRequest tests this. If it returns true, cookies are enabled and the remaining steps are unnecessary. The following example shows method doGet( ) of a servlet implementing session tracking.
Example: Session tracking
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
try {
// hole die aktuellen Einstellungen der Session
HttpSession session = req.getSession(true);
Cart cart = (Cart) session.getAttribute("shoppingCart");
if (cart == null) {
cart = new Cart( );
session.setAttribute("shoppingCart", cart);
}
// erzeuge den DOM-Baum
Document doc = CartDOMProducer.createDocument(cart);
// bereite die XSLT-Transformation vor
Transformer trans = StylesheetCache.newTransformer(
this.xsltFileName);
// ermögliche Session-Tracking ohne Cookies
if (!req.isRequestedSessionIdFromCookie( )) {
String sessionID = session.getId( );
trans.setParameter("global.sessionID",
";jsessionid=" + sessionID);
}
// sende die Webseite zum Nutzer zurück
res.setContentType("text/html");
trans.transform(new javax.xml.transform.dom.DOMSource(doc),
new StreamResult(res.getWriter( )));
} catch (ParserConfigurationException pce) {
throw new ServletException(pce);
} catch (TransformerConfigurationException tce) {
throw new ServletException(tce);
} catch (TransformerException te) {
throw new ServletException(te);
}
}The first crucial line tests whether the session was created without a cookie:
if (!req.isRequestedSessionIdFromCookie( )) {On the first request, no cookie exists because the servlet has not yet had a chance to create one. On subsequent requests it is also absent if the user disabled cookies. In both cases, the session identifier comes from the instance of HttpSession:
String sessionID = session.getId( );The servlet API also generates a random session identifier. You must store it and pass it to the stylesheet as a parameter:
trans.setParameter("global.sessionID",
";jsessionid=" + sessionID);The servlet also prefixes the identifier with string ";jessionid=". This saves the XSLT stylesheet from testing whether the session ID is empty. The value of global.sessionID can now be appended to all URLs:
<a href="/beliebiger_link{$global.sessionID}">hier klicken</a>As a result, URLs remain unchanged when cookies are enabled; otherwise they are modified for session tracking. A larger stylesheet follows.
Example: XSLT stylesheet for session tracking
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml">
<!--
*********************************************************************
** global.sessionID : Wird für das Umschreiben von URLs verwendet, um
** Session-Tracking ohne Cookies zu ermöglichen.
****************************************************************** -->
<xsl:param name="global.sessionID"/>
<!-- Dieses Stylesheet erzeugt XHTML -->
<xsl:output method="xml" indent="yes" encoding="ISO-8859-1" doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>
<!--
*********************************************************************
** Dieses Template erzeugt das Gerüst des XHTML-Dokuments.
****************************************************************** -->
<xsl:template match="/">
<html>
<head>
<title>Online-Shop</title>
</head>
<body>
<!-- Erzeuge auf dieser Seite ein Formular -->
<form method="post" action="/chap8/shopping{$global.sessionID}">
<h1>Online-Shop</h1>
...der Rest der Seite wurde ausgelassen
</form>
</body>
</html>
</xsl:template>
<xsl:template match="cart">Betätigen Sie den Link, um weiterzugehen: <a href="/shopping/moveNext{$global.sessionID}?param=value"/>weiter</a>
...
</xsl:template>
</xsl:stylesheet>The stylesheet illustrates the three main components of XSLT session tracking. First, the session identifier is passed as a parameter:
<xsl:param name="global.sessionID"/>It is then used for the form action:
<form method="post" action="/chap8/shopping{$global.sessionID}">Finally, it is used for every hyperlink:
<a href="/shopping/moveNext{$global.sessionID}?param=value"/>weiter</a>String ?param=value was appended to show that request parameters follow the session identifier. The complete URL therefore looks like this:
"http://localhost:8080/shopping/moveNext;jsessionid=298ulkj2348734jkj43?param=value"
Session tracking is essential. This approach works even with browser cookies disabled. Always test your web application with cookies disabled to ensure every URL receives the correct session identifier.
Copyright © 2002 O'Reilly Verlag GmbH & Co. KG
You may print the online version for your private use.
Otherwise, this chapter from “Java und XSLT” is subject to the same conditions as the bound edition. The work, including all its parts, is protected by copyright. All rights reserved, including reproduction, translation, microfilming, and storage and processing in electronic systems.
O’Reilly Verlag GmbH & Co. KG, Balthasarstraße 81, 50670 Köln, kommentar(at)oreilly.de