Friday, October 24, 2008

Sharing Java Applet Sessions in Firefox

There is a known problem in JEP (Java Embedding Plugin) for Firefox in which new sessions (or no sessions at all) are used for every new Java applet request to a servlet. This can be problematic for applets that requests data or URL from a servlet requiring authentication or a login. To get around this problem, you can pass in the current HTLM document's cookie as a Java applet parameter, and then use the cookie in the HttpServletRequest's Cookie request parameter.

In your HTML applet code, just add the document's cookie as a parameter. (Note that I'm writing the HTML applet code in JavaScript to dynamically get the document's cookie.)

<script language="JavaScript" type="text/javascript">
   document.write("browserCookie='" + document.cookie + "'");
Then in your servlet, use the browserCookie parameter value as the Cookie property in the HttpServletRequest.
import javax.swing.JApplet;

public class MyApplet extends JApplet{

   public void doIt(URL url){
      URLConnection urlConnection = url.openConnection();
      String cookie = getParameter("browserCookie");
      urlConn.setRequestProperty("Cookie", cookie);

      // Now you can do what you need with the URLConnection
      // (e.g. open up an InputStream to read the data)
      // using the same cookie session.


For more information check out these postings: