![]() ![]() ![]() |
![]()
Building Java Servlets with JBuilder Part III NOTE: The views and information expressed in this document represent those of its author(s) who is solely responsible for its content. Borland does not make or give any representation or warranty with respect such content.
Return to Part I Example: Creating a Simple HTTP/RMI/CORBA Test Applet The purpose of this topic is to help you become acquainted with invoking a servlet from an applet using the HTTP, RMI, or CORBA transport. This example continues from Example: creating a JDBC servlet as RMI server and Example: creating a JDBC servlet as CORBA server. In this example you will learn how to:
See also:
A Simple Test Client Example 4-1: ITransportClient.java package JBExamples.database.applets; public interface ITransportClient { public String executeQuery(String query) throws Exception ; }
Example 4-2: HTTPTransportClient.java package JBExamples.database.applets; import java.util.*; import java.net.*; import java.io.*; public class HTTPTransportClient implements ITransportClient { String servletLoc; public HTTPTransportClient(String servletLoc) { this.servletLoc = servletLoc; } /** * This method illustrates how to communicate to the JDBCServlet using * the HTTP transport. * This method also illustrates how general applet to servlet communication * can be carried out. */ public String executeQuery(String queryString) throws Exception { StringBuffer results = new StringBuffer(); //The value of dbquery has to be urlencoded to be passed through http. String postData = "dbQuery="+URLEncoder.encode(queryString); URL action = new URL(servletLoc); URLConnection url = action.openConnection(); url.setDoInput(true); url.setDoOutput(true); url.setUseCaches(false); url.setRequestProperty("Content-type", "application/x-www-form-urlencoded"); url.setRequestProperty("Content-length", "" + postData.length()); // Write out post data DataOutputStream out = new DataOutputStream(url.getOutputStream()); out.writeBytes(postData); out.flush(); out.close(); // Get response DataInputStream in = new DataInputStream(new BufferedInputStream(url.getInputStream())); String line; while(null != ((line = in.readLine()))) results.append(line + "\n"); return results.toString(); } } The following example illustrates how to invoke methods of the database servlet remotely using RMI. Example 4-3: RMITransportClient.java package JBExamples.database.applets; //Packages for RMI support import java.rmi.registry.*; import java.rmi.server.UnicastRemoteObject; import java.rmi.*; //RMI objects import JBExamples.database.servlets.rmi.IDBQuerier; import JBExamples.database.servlets.rmi.IDataTable; public class RMITransportClient implements ITransportClient { String serverName; IDBQuerier dbQuerier = null; public RMITransportClient(String serverName) throws Exception { this.serverName = serverName; //Install a security manager. Doing this will allow this client to load //stubs remotely. if (System.getSecurityManager() == null) System.setSecurityManager(new RMISecurityManager()); //Get a remote reference to the JDBCRmiServlet object dbQuerier = (JBExamples.database.servlets.rmi.IDBQuerier)Naming.lookup(serverName); } /** * This method illustrates how to communicate to the JDBCRmiServlet using * the RMI transport. */ public String executeQuery(String queryString) throws Exception { if( dbQuerier == null ) return "DBQuerier is null"; StringBuffer results = new StringBuffer(); //Try to fetch an IDataTable object from the IDBQuerier. IDataTable //should contain the results of the query. IDataTable dataTable = dbQuerier.getResultTable(queryString); if( dataTable == null ) return "Data is null"; return dataTable.toTableString(); } } Example 4-4: CORBATransportClient.java package JBExamples.database.applets; //Packages for CORBA support import org.omg.CORBA.*; import JBExamples.database.servlets.corba.IDBQuerierHelper; //CORBA objects import JBExamples.database.servlets.corba.IDataTable; import JBExamples.database.servlets.corba.IDBQuerier; public class CORBATransportClient implements ITransportClient { //Server's identifier String serverName; IDBQuerier dbQuerier = null; public CORBATransportClient(String serverName) throws Exception { this.serverName = serverName; //Inititialize the orb String[] args = new String[0]; ORB orb = ORB.init(args, null); //Get a remote reference to the JDBCCorbaServlet object dbQuerier = IDBQuerierHelper.bind(orb, serverName); } public String executeQuery(String queryString) throws Exception { StringBuffer results = new StringBuffer(); if( dbQuerier == null ) return "DBQuerier is null"; //Try to fetch an IDataTable object from the IDBQuerier. IDataTable //should contain the results of the query. IDataTable dataTable = dbQuerier.getResultTable(queryString); if( dataTable == null ) return "Data is null"; return dataTable.toTableString(); } } Example 4-5: JDBCApplet.java package JBExamples.database.applets; import java.awt.*; import java.awt.event.*; import java.applet.*; import java.net.*; import java.io.*; import java.util.Hashtable; /* * A class that shows how to access an RMI or CORBA servlet from an * applet. * Since both objects are also servlets they both can be accessed via the * HTTP transport. */ public class JDBCApplet extends Applet implements Runnable { Thread t = null; TextArea textArea; TextField textField; Button queryButton; Choice jdbcClients; Hashtable transportClients = new Hashtable(); String HTTP = "HTTP"; String RMI = "RMI"; String CORBA = "CORBA"; //A variable that specifies the name of the servlet to be accessed using //the HTTP transport. The servlet is accessed using the servlet's alias. //Servlet aliasing can be set through the servlet runners admin tool. //The alias to the JDBCRmiServlet is assumed to be set to RMIServlet //The alias to the JDBCCorbaServlet is assumed to be set to CORBAServlet //String servletName = "CORBAServlet"; //Use the corba servlet as the plain servlet String servletName = "RMIServlet"; //Use the rmi servlet as the plain servlet //Construct the applet public JDBCApplet() { } //Initialize the applet public void init() { super.init(); try { jbInit(); //Initialize transport clients transportClients.put( HTTP, new HTTPTransportClient(getCodeRoot()+"/servlet/"+servletName)); transportClients.put( RMI, new CORBATransportClient("DBQuerier") ); transportClients.put( CORBA, new RMITransportClient("DBQuerier") ); } catch (Exception e) { e.printStackTrace(); } } //Component initialization private void jbInit() throws Exception { setSize(new Dimension(300, 300)); setLayout(new BorderLayout()); //Build the mainPanel Panel mainPanel = new Panel(); mainPanel.setLayout(new BorderLayout()); //Build north part of mainPanel Panel northPanel = new Panel(); northPanel.setLayout(new GridLayout(2,2) ); northPanel.add(new Label("Query String: ")); textField = new TextField(); textField.setColumns(25); northPanel.add(textField); jdbcClients = new Choice(); jdbcClients.add(HTTP); jdbcClients.add(RMI); jdbcClients.add(CORBA); northPanel.add(new Label("JDBC Client Call Through:")); northPanel.add(jdbcClients); mainPanel.add("North", northPanel); //Build a blank textArea and center in the panel textArea = new TextArea(); textArea.setEditable(false); mainPanel.add("Center", textArea); //Build the button panel Panel buttonPanel = new Panel(); this.queryButton = new Button("Query"); this.queryButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent event) { try { String selectedClient = jdbcClients.getSelectedItem(); //Get the correct transport client ITransportClient client = (ITransportClient)transportClients.get(selectedClient); doQuery(client); } catch(Throwable e) { e.printStackTrace(); textArea.setText("An exception occured trying to locate the server.\n"+ "Here it is: "+e.toString()); textArea.show(); } } } ); buttonPanel.add("Center", queryButton); mainPanel.add("South", buttonPanel); add("Center", mainPanel); } public void run() { if( t == null ) { this.t = new Thread(this); t.start(); } } public void stop() { if( t != null ) { t.stop(); t = null; } } public Insets insets() { return new Insets(10,10,10,10); } /** * Execute the query using the given ITransportClient */ public void doQuery(ITransportClient client) { String queryString = textField.getText(); try { String results = client.executeQuery(queryString); textArea.setText( results ); } catch(Exception e) { e.printStackTrace(); textArea.setText("An exception occured trying to execute the query.\n"+ "Here it is: "+e.toString() ); } textArea.show(); } /** * Get Applet information */ public String getAppletInfo() { return "Applet Information"; } /** * Get parameter info */ public String[][] getParameterInfo() { return null; } /** * Find the code root. */ private String getCodeRoot() { String codeRoot; String codeBase = getCodeBase().toString(); int i=0, count=0; while(count < 3) { if(codeBase.charAt(i++) == '/') count++; if(i > codeBase.length()) break; } if(i < codeBase.length()) codeRoot = codeBase.substring(0, i); else codeRoot = codeBase; while(codeRoot.endsWith("/")) codeRoot = codeRoot.substring(0, codeRoot.length()-1); if(codeRoot.startsWith("http://") == false && codeRoot.startsWith("file://") == false ) codeRoot = "http://" + codeRoot; return codeRoot; } } <TITLE> JDBC Applet Page </TITLE> </HEAD> <BODY> JDBCApplet will appear below in a Java enabled browser work<BR> <APPLET CODEBASE = "." CODE = "JBExamples.database.applets.JDBCApplet.class" NAME = "JDBCApplet" WIDTH = 400 HEIGHT = 300 HSPACE = 0 VSPACE = 0 ALIGN = middle > </APPLET> </BODY> </HTML>
Once the RMI registry, and Visibroker have started up, the next step is to start up the Web Server. Before starting up the web server make sure your servlets are set to load on init, if you have not done so, see the section Loading On Init. Using appletviewer throught the DOS prompt, make sure your system classpath is set to use JBuilderÆs database classes. The rising popularity of Java Servlet technology is at an unrivaled pace that signifies the hungering success of the internet. This relatively new technology is indeed a quieting factor for those demanding efficient internet solutions. For more information on servlets, visit the Live Software web site at http://www.livesoftware.com.
Back To Top © 1998 by Live Software, Inc., San Diego, California 92121. All rights reserved. No part of this document may be reproduced, stored in a retrieval system, or transcribed, in any form or by any means û electronic, mechanical, photocopying, recording, or otherwise û without the prior written permission of the publisher, Live Software, Inc., 5703 Oberline Dr. Suite 208, San Diego, California, 92121. |