This demonstrates how to pass a Java servlet session ID from a web application through to an applet.
I was originally aiming to do this in a dynamically generated JNLP file (generated from a JSP), but it turns out that rather than the web browser downloading the JNLP file and passing its path to the JVM, it simply passes the URL, so the JNLP file is still requested in a different session.
This implementation uses a different technique. It simply passes the cookie needed as a parameter to the applet. The JNLP can therefore be static, although its currently still a JSP.
The application has a trivial REST web service, which the applet calls. The web service is protected via a servlet filter which forbids any connection which does not have a current session. The "Login" link on the
index.jsp file invokes a servlet which creates a session.
When you initially go the main page (index.jsp) the
applet tag is populated with the current cookies for the current domain. If this is the first time you have visited the page, or if you have recently restarted the application, you will not have current or valid cookies. Therefore, the cookies passed to the applet will be incorrect, and the applet will not be able to successfully request data from the webservice. It will indicate this error.
Once you've followed the "Login" link, a session will be created, and you'll have a valid session. The login servlet redirects the browser to the
index.jsp, the page will repopulate the parameters for the applet with the valid cookie values and the applet will restart using in the correct cookies. It will now indicate that it can access the webservice successfully.
Running the application
To run the demonstation application you must have:
- Java SE 7 installed (the concepts do not require it, but this implementation does);
- The Java Plugin properly installed and working;
- Apache Maven installed and working with access to Central.
You don't need git installed to get the code, as you can simply download master. Unzip, or clone, the code, open a command prompt and change to the directory root directory of the project, the first one containing a
pom.xml file. Then enter:
$ mvn install tomcat7:run-war
This will build all the code and start the webserver. Then simply navigate to the index.jsp page to experiment with the demo.