In my jsp page I have 2 combo boxes--data of 2nd comboBox is dependent on the 1st. The data for both is previously obtained from a database.

Luigi Viggiano

Well, this is very complex :), I faced the same problem

I used an applet loaded inside JSP. The applet's finder-methods are invoked by some JavaScript in the page, when the first combo changes. The applet loads data from db passing thru a servlet (a JSP in this case). Then the Applet calls a JavaScript populating the second combo...
This is comuni.jsp:


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/transitional.dtd">
<html xmlns="http://www.w3.org/TR/xhtml1">
  <head>
    <script>
    <!--
        // ripulisce la combo
        function clearCombo(combo) {
          var numOptions = combo.length;
          for (var i = 0; i < numOptions; i++)
            combo.options[0] = null;
        }

        // aggiunge un comune alla combo dei comuni
        function addComune(codice, descrizione) {
          var comuni = document.hostform.comune.options;
          var option = new Option(descrizione, codice);
          comuni[comuni.length] = option;
        }

        // chiama il metodo findComuni sull' applet
        function findComuni(codiceProvincia) {
          document.comuniApplet.findComuni(codiceProvincia);
        }

        // funzione richiamata dall' onChange della combo delle province
        function changeComboComuni(codiceProvincia) {
          clearCombo(document.hostform.comune);
          findComuni(codiceProvincia);
        }

        //-->
      </script>
  </head>
  <body>
    <applet MAYSCRIPT
            archive="<%= request.getContextPath() %>/appletComuni.jar"
            code="ComuniApplet.class"
            name="comuniApplet"
            width="0"
            height="0"
            vspace="0"
            hspace="0">
    </applet>

    Test comuni/provincia...

    <form name="hostform" method="get" action="">
      <select name="provincia"
              onchange="javascript:changeComboComuni(provincia.options[provincia.selectedIndex].value)">
        <option value=""></option>
        <option value="01 ">TO</option>
        <option value="02 ">MI</option>
      </select>
      <select name="comune">
      </select>
      <input type="submit" />
    </form>
  </body>
</html>
Here comes the applet:

import java.applet.*;
import netscape.javascript.*;
import java.net.*;
import java.util.*;
import java.io.*;

public class ComuniApplet extends Applet implements Runnable {
    // costanti identificative dei metodi del thread
    public static final int OP_FIND_COMUNI = 0;
    public static final int OP_NO_OPERATION = -1;

    private int operation = OP_NO_OPERATION;

    private JSObject jsObject;
    private URL codebase;
    private Object lock; // monitor usato per wait/notify
    private String codiceProvincia;

    // cache locale dei dati già prelevati dal server
    private Vector cacheProvince = null;
    private Properties cacheComuni = new Properties();

    public ComuniApplet() {
    }

    public void start() {
        //inizializzazione membri dell' applet
        jsObject = JSObject.getWindow(this);
        lock = new Object();
        codebase = getCodeBase();

        // creazione del thread
        Thread appletThread = new Thread(this);
        appletThread.start();
    }

    public void run() {
        while (true) {
            synchronized (lock) {
                try {
                    lock.wait();
                } catch (InterruptedException ex) {
                    //System.out.println("Applet interrotta dal browser");
                    //ex.printStackTrace();
                    operation = OP_NO_OPERATION;
                    break;
                }
            }

            switch (operation) {
                case OP_FIND_COMUNI :
                    doFindComuni();
                    break;
            }
        }
    }

    public void findComuni(String codiceProvincia) {
        if ((null == codiceProvincia) || "".equals(codiceProvincia))
            return;

        this.operation = OP_FIND_COMUNI;
        this.codiceProvincia = codiceProvincia;

        // quando il thread si sveglia chiama doFindComuni()
        synchronized(lock) {
            lock.notify(); // sveglia il thread
        }
    }

    private Vector getVectorFromPath(String path)
        throws MalformedURLException, IOException {

        Vector result = new Vector();
        URL url = new URL(codebase.getProtocol(),
                          codebase.getHost(),
                          codebase.getPort(),
                          path);
        InputStream is = url.openStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;
        while ((line = br.readLine()) != null ) {
            int sepIndex = line.indexOf('=');
            if (sepIndex == -1) {
                continue;
            }
            String codice = line.substring(0, sepIndex);
            String descrizione = line.substring(sepIndex + 1);
            result.addElement(new String[] {codice, descrizione});
        }
        return result;
    }

    public void doFindComuni() {
        String path = "/anagrafe/anagrafe/controller/comuni.jsp?provincia=" +
                      URLEncoder.encode(codiceProvincia);

        try {
            Vector vect = (Vector)cacheComuni.get(codiceProvincia);
            if (vect == null) {
                vect = getVectorFromPath(path);
                cacheComuni.put(codiceProvincia, vect);
            }

            Enumeration keys = vect.elements();
            while (keys.hasMoreElements()) {
                String[] comune = (String[])keys.nextElement();
                addComune(comune[0], comune[1]);
            }

        } catch (MalformedURLException malfURLEx) {
            malfURLEx.printStackTrace();
        } catch (IOException ioEx) {
            ioEx.printStackTrace();
        }
    }

    /**
     * Callback al JavaScript "addComune(codice, descrizione)"
     */
    public void addComune(String codice, String descrizione) {
        jsObject.call("addComune", new Object[] {codice, descrizione});
    }

}
Note: i used a wait/notify thread scheme, to load data from the URL, because Netscape 6 gives network access based on thread. I also used Java 1 classes only because most of Netscape 4.x are not Java2 enabled.

And here the JSP that returns the query from the DB:


<%@ page language="java"
         contentType="text/html"
%>
<%@ page import="java.util.*" %>
<%@ page import="VOComune" %>
<%
    String provincia = request.getParameter("provincia");
    while (provincia.length() < 3) {
        provincia += " ";
    }

    try {
        Sportello sportello = new SportelloClient().getSportello();

        Collection coll = sportello.getComuni(provincia);
        Iterator iter = coll.iterator();
        while (iter.hasNext()) {
            VOComune comune = (VOComune)iter.next();
            out.println(comune.getCodice() + "=" + comune.getDenominazione());
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
%>
I used the code listed above to play with 3 different combo (state, region, city), I cutted some code (let's hope nothing important ;-) ).

Sorry for the huge post; best luck.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact