Access parameters passed in the URL (this howto is deprecated)Tag(s): DEPRECATED
import java.applet.Applet;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
@SuppressWarnings("serial")
public class AppletUrlParams extends Applet {
HashMap<String,String> parmsMap ;
public void init() {
/*
dump to the console the URL, the search and search values
the URL http://myserver.com/mypage.html?value1=x&value2=y&value3=z
the search value1=x&value2=y&value3=z
the values value1=x
value2=y
value3=z
then the values are stored in a map for easy reference.
ex. String name = parmsMap.get("name")
*/
try {
doit();
dumpMap(parmsMap);
//System.out.println("name is " + parmsMap.get("name"));
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public void doit() throws UnsupportedEncodingException {
String completeURL = getDocumentBase().toString();
System.out.println("Complete URL: " + completeURL);
int i = completeURL.indexOf("?");
if (i > -1) {
String searchURL = completeURL.substring(completeURL.indexOf("?") + 1);
System.out.println("Search URL: " + searchURL);
initMap(searchURL);
}
}
public void initMap(String search) throws UnsupportedEncodingException {
parmsMap = new HashMap<String,String>();
String params[] = search.split("&");
for (String param : params) {
String temp[] = param.split("=");
parmsMap.put(temp[0], java.net.URLDecoder.decode(temp[1], "UTF-8"));
}
}
public void dumpMap(Map<?,?> map) {
System.out.println("--------");
for (Map.Entry<?,?> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println("--------");
}
}
Test it here.
The result in the Java console should be :
key : firsparam value : Hello key : secondparam value : World key : thirdparam value : Hello World
A note from mm300
Access parameters passed in the URL in line String completeURL = getDocumentBase().toString(); is a trap: Netscape won't return the whole URL, but only domain name and directory but without .html and parameters. In IE and Firefox, it's ok.
So if we have www.domain.com/applets/win.html?winner=Maurice
Then getDocumentBase () returns :
NS: www.domain.com/applets/
IE: www.domain.com/applets/win.html?winner=Maurice
mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com