Load/Save Cookies inside an Applet


import java.applet.Applet;

import java.util.StringTokenizer;
import netscape.javascript.JSObject;

public class CookieTest extends Applet {

	public void start() {
		System.out.println("Saving cookie:");
		saveCookie(this, "blah", "captain");
		System.out.println("Cookie is:");
		System.out.println(loadCookie(this, "blah"));
	}
	
	public String loadCookie(Applet applet, String key) {
		if (applet != null) {
			try {
				applet = lwjglMayscriptFix(applet);
				String cookie =(String)JSObject.getWindow (applet).eval ("document.cookie");
				StringTokenizer st = new StringTokenizer(cookie, ";", false);
				
				while (st.hasMoreTokens()) {
					String psh = st.nextToken().trim();
					StringTokenizer z = new StringTokenizer(psh, "=", false);
					String token = z.nextToken();
					if (token.equals(key)) return z.nextToken();
				}
				
			} catch (Exception e) {
				System.out.println("not able to load cookie");
			}
		}
		return null;
	}

	public void saveCookie(Applet applet, String key, String value) {
		try {
			applet = lwjglMayscriptFix(applet);
			JSObject.getWindow (applet).eval ("document.cookie ='" + key + "=" + value + ";expires=Friday, 31-Dec-20 23:59:58 GMT';");
		} catch (Exception e) {
			System.out.println("not able to save cookie");
		}
		
	}
	
	public Applet lwjglMayscriptFix(Applet applet) {
		if (applet != null) {
			boolean possibleFix = true;
			Applet lastApplet = applet;
			Applet zr;
			
			java.util.Enumeration ez = applet.getAppletContext().getApplets();
			while  (ez.hasMoreElements() && (zr = (Applet)ez.nextElement()) != null) {
				if (applet != zr) possibleFix = false;
				lastApplet = zr;
			}
			//SHOULD BE A BETTER FIX, SOMETHING LIKE CHECK NAME VARIABLE
			//OF THE APPLET TO ASSIGN THE RIGHT APPLET FOR THE COOKIE
			if (possibleFix) applet = lastApplet;
		}
		return applet;
	}
}

Also make sure to include “plugin.jar” into the classpath, it should be located in the same directory as “rt.jar”.

What’s wrong with using split(";") instead of StringTokenizer?

EDIT: Either way, it doesn’t work for me :confused: The cookie doesn’t seem to save after refreshing the page.

Maybe… create servlet class to handle the cookie?

Never mind I got it to work. I was testing my applet in localhost, and since Java blocks all interactions on localhost it wasn’t working.