How to access parameters passed in the URL in Applet
Often times, Applet is require to read the parameters that passed in the URL. For example,
URL
http://.../applet/testIt.html?test.html?key1=value1&key2=value2&key3=value3
Applet is require to read the parameter values
key1=value1&key2=value2&key3=value3
In this example, you will see how can Applet access the parameters “key1=value1&key2=value2&key3=value3″.
1. Create a Applet class
During Applet initialize stage, Applet will get the full URL with “getDocumentBase().toString();” method and parse the parameter one by one and store it into HashMap for later use.
package com.mkyong.applet; import java.applet.*; import java.awt.Graphics; import java.util.HashMap; import java.util.Map; import java.util.StringTokenizer; public class AppletExample extends Applet { Map<String, String> paramValue = new HashMap<String, String>(); public void init() { String url = getDocumentBase().toString(); if (url.indexOf("?") > -1) { String paramaters = url.substring(url.indexOf("?") + 1); parseParam(paramaters); } } //parse the URL parameter private void parseParam(String parameters){ StringTokenizer paramGroup = new StringTokenizer(parameters, "&"); while(paramGroup.hasMoreTokens()){ StringTokenizer value = new StringTokenizer(paramGroup.nextToken(), "="); paramValue.put(value.nextToken(), value.nextToken()); } } public void paint( Graphics g ) { int x = 20; int y = 50; int counter = 10; for (Object key: paramValue.keySet()) { g.drawString("key : " + key + " value : " + paramValue.get(key),x,y+counter); counter += 10; } } }
2. Create a HTML page
Create a simple HTML page and inlcude the Applet.
<html> <head><title>Testing</title></head> <body> <applet width=300 height=300 code="com.mkyong.applet.AppletExample.class"> </applet> </body> </html>
3. Run it
Double click on your HTML page, you will see Applet display following result :
key : key3 value : value3 key : key2 value : value2 key : key1 value : value1