No Cookies Required
As explained in How
This Site Works, the HTML pages on this site are dynamically
generated. This allows me to do some interesting things, such
as automatically switching between a screen-friendly and
a printer-friendly version of the site without writing two sets
of pages. To do this kind of thing, however, my web application
needs to track state information about your browser session.
Normally, this is done using cookies, which are little
pieces of server-generated data that get stored locally on your
machine. Your browser sends the data back to the server every
time it requests a page.
Encoding Session Information
While convenient, some people find cookies objectionable,
for various reasons. HTTP, though, is a sessionless
protocol, so if cookies are not available then you
must do session tracking using other means.
One alternative to using cookies is to encode
some kind of session identifier (ID) in the URL of the
page. For example, given a URL like:
You could add a session ID using a query parameter:
Or you could add extra "path" information:
The latter approach is preferable, because then the
session information doesn't get mixed up with the query
parameters used by the site's forms. As it turns out,
the HTTP specification makes this approach very easy
to do because it allows the URL to append extra information
to a URL path by separating it with a semicolon, like
URL Encoding in Java
specification makes it trivial to add this session
information to the URL:
String url = "/about/index.html";
HttpServletResponse res = .... // some response
url = res.encodeURL( url );
From a JSP page, you can do this very easily using
the JSTL <c:url> tag:
For the session tracking to work, though, you
must encode every internal link in your site.
In other words, every link you generate in your
markup that goes to another page in your site
must run through the encoding procedure.
You can't do this kind of thing with static pages.
are available. But it will work just as well
without them. If the servlet container (Tomcat,
in this case) detects that cookies are enabled,
method simply returns the URL that was passed
to it, without any additional encoding. It makes
things pretty seamless!