Cookies are the most common means of creating sessions with clients. Sessions are a means of tracking client information through a series of requests. The cookie example (see Listing 12.7) could have been used to store a sessions ID, but the Java HttpSession class makes session tracking much easier.
To create a session, use HttpRequest's getSession() method. This returns a HttpSession instance. HttpSession is a simple interface to the more complicated behavior of a session management subsystem. Using the HttpSession object from Jython differs only from Java in the syntax and the automatic bean properties for the object's get* methods.
Once you have a HttpSession instance, passing data through the session is just a matter of using key, value pairs with putValue(key, value) and value = getValue(key).
Listing 12.8 Session Management
# File: session.py from javax import servlet from javax.servlet import http class session(http.HttpServlet, servlet.RequestDispatcher): def doGet(self, req, res): sess = req.session res.contentType = "text/html" out = res.getWriter() name = req.getParameterValues("name") value = req.getParameterValues("value") if name and value: sess.putValue(name, value) print >>out, (""" <html> <body> <H3>Session Test</H3> Created at %s<br> Last Accessed = %s<br> <u>Values:</u>""" % (sess.creationTime, sess.maxInactiveInterval) ) print >>out, "<ul>" for key in sess.getValueNames(): print >>out, "<li>%s: %s</li>" % (key, sess.getValue(key)) print >>out, "</ul>" print >>out, """ <HR><P>Use this form to add a new values to the session</P> <form action="session.py" method="GET"> <P>Name:<br><INPUT type="text" name="name" size="30"></P> <P>Value:<br><INPUT type="text" name="value" size="30"></P> <INPUT type="submit" name="button" value="submit"> </body> </html> """
After saving the session.py file from Listing 12.8 in the %TOMCAT_HOME%\ webapps\jython directory, point your browser to http://localhost:8080/jython/session.py. Use the web form to add some variables to the session to confirm it is working, and even try disabling cookies to see how the URL rewriting works. Figure 12.4 is the session.py results after adding a series of arbitrary values (results depend on the values added).
Figure 12.4. Session variables with session.py.