URLConnection


The applet may communicate with a server-side servlet in several ways, including conventional socket connections.  However, a preferred way is through a URLConnection that uses HTTP as transport.   The mechanics of setting up a client-side URLConnection with a servlet are illustrated in the following code:

private ResponseBean sendRequest( RequestBean requestBean ) {

     
	try {

     
    		
    		URL documentBase = getDocumentBase();
		String urlString = "http://";
		urlString += documentBase.getHost() + ":";
		urlString += documentBase.getPort();
		urlString += "/" + Context.getProjectName();
		urlString += "/servlet/jbs.abapplet.servlet.ServletAB";
		URL url = new URL( urlString );
		URLConnection connection = url.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setUseCaches (false);
		connection.setRequestProperty("Content-Type", "application/octet-stream");
		// this is a real kludge that may change
		//connection.setRequestProperty("Cookie", "JSESSIONID=0000" + jsessionid );
		OutputStream os = connection.getOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream( os );
		oos.writeObject( requestBean );
		oos.flush();
		oos.close();
		InputStream is = connection.getInputStream();
		ObjectInputStream ois = new ObjectInputStream( is );
		ResponseBean responseBean = ( ResponseBean )(ois.readObject());

		ois.close();

		return responseBean;
	} catch (MalformedURLException e) {
		System.out.println("MalformedURLException: " + e);
		return null;
	} catch (IOException e) {
		System.out.println("IOException: " + e);
		return null;
	} catch (ClassNotFoundException e) {
		System.out.println("ClassNotFoundException: " + e);
		return null;
	}
}

The method is defined to include a RequestBean that includes all data required by the servlet as well as an indication of the user's intended action.  In turn, a ResponseBean is expected back.  Both beans are handled using Object-based I/O.

Once the connection is setup, writing and reading are straight-forward, although note the flushing and closing of connections.

Again, code not needed for this particular application is shown that illustrates how a JSESSIONID reference may be passed back to the servlet in the form of a cookie that ensures that the same server-side session object is being used for applet interactions as is being used for JSPs.  here, the JSESSIONID is stored in a global variable, jsessionid, that is read in as a parameter from the applet tag.