Is there any way to use cookies in applets without having to sign the applet and have the wonderful security dialogue popup? If not then applets are really quite useless for any sort of rich Internet applications if you care about user experience.
the most successful way I’ve seen this done is by using php, use the applet to send/recieve information to/from php and get php to handle all the storing/retrieving of cookies.
Yes but how do you ID a computer when you re-run an applet, do you just get them to log-in every time?
No the cookie is saved to the browser cache of the local computer and not on the server. So you will get what ever value you saved there.
If your looking to identify individual computer somehow then have a look at this thread.
Access cookies in Java:
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 requireFix = true;
Applet lastApplet = applet;
Applet zr;
java.util.Enumeration ez = applet.getAppletContext().getApplets();
while (ez.hasMoreElements() && (zr = (Applet)ez.nextElement()) != null) {
if (applet == zr) requireFix = 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 (requireFix) applet = lastApplet;
}
return applet;
}
}
AppletCode (keyword is MAYSCRIPT):
<applet width="320" height="240" code="CookieTest" MAYSCRIPT=true></applet>
One other cookie issue is, if you cant access cookie via a frame use this in your php file:
header('P3P:CP="IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"');
Cheers guys,
I was getting depressed after the CookieHandler API was looking like it was going to do everything for me and then I realised CookieHandler.setDefault() required signed applets.