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.


Testing

 


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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
1 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
1 Comment authors
bill Recent comment authors
newest oldest most voted
bill
Guest
bill

can those params be parsed into a cookie?