Solved

struts drop-down

Posted on 2006-11-07
13
1,912 Views
Last Modified: 2007-12-19
hi experts

I have a scenario where i have to develop  an applicaiton with 5 drop down fields.
but all those 5 dropdowns are dependent on each other.

My 5 drop-down fields will be

State

Region

County

Municipality

Hospitals


State drop-down will have 3 states. "Each" of those 3 states will have certian regions,
each of those regions will have certain Counties, each of those counties will have certian municipalities and each of those
municipalities will have certian hospitals.

so if my states are NJ,NY and PA.
when user selects NJ in the "state" dropdown, all regions in NJ should be automatically populated in "region" dropdown. Now if user selects a specific Region in region dropdown ,all counties for that selected region should be automatically populated in county dropdown.
If user selects a specific county ,all municipalities for that selected county should be automatically populated in municipality dropdown.
If user selects a specific municipality , all hospitals for that selected municipality should be populated in hospital dropdown..

something like www.cars.com. If i change "Make:"  , "Model:" should change accordingly.

any ideas how to design such an application using struts and ( without using javascript ).


thanks
J
 
0
Comment
Question by:jaggernat
  • 7
  • 6
13 Comments
 
LVL 14

Expert Comment

by:boonleng
Comment Utility
Because the dropdown options is dynamic, if you want to do it without javascript, then every time user change the drop down box, the form will need to submit back to server to retrieve the options and refresh the page.

I would suggest using javascript as its more user friendly.
You can either load all the data to javascript array, then populate the data from array to dropdown according to selection. Or use Ajax (preferable) to retrieve the options from server(behind the scene) each time user select the options.

0
 
LVL 10

Author Comment

by:jaggernat
Comment Utility
I actually have a javascript working solution to this , but javascript is a real pain and i want to avoid it.
this is what i am doing:

I have a java util class which is calling the database and using StringBuffer class i am generating the necessary xml in this format
<state>
  <region>
     <county>
         <municipality>
               <hospital>

I am loading the above xml in my javascript and reading the xml nodes with XPath and populating the dropdown fields.

So once i have the above xml, is there any way i can avoid javascript and use something else (probably in struts) which can read the xml
and populate the drop-down fields.

thanks
 
0
 
LVL 14

Expert Comment

by:boonleng
Comment Utility
Sorry for the late reply, being busy for UAT.

If you wanna avoid javascript, then you will have to submit the form to server during onchange on the dropdown, then the struts action will read the xml and populate the options array list to form bean/request attribute. Once the page refeshed, the dropdown will read the option array list from form bean/request attribute.

Using Ajax will be similar to above, struts action still used to read the xml file, but the return output will be javascript to populate the dropdown.
Example
out.println("var dropdown =  document.getElementById('region');");
out.println("dropdown.options[0] = new Option('" + xmldata + "', '" + xmldata + "');");
0
 
LVL 10

Author Comment

by:jaggernat
Comment Utility
thanks boonleng. what you said is pretty intresting!

>>>submit the form to server during onchange on the dropdown
so onchange i call a javascript which submits the jsp right?

>>>>struts action will read the xml
how can i make my action class method read the xml?




Do you know any website which shows how to use ajax  with jsp/struts  for my above scenario.

also i posted this question on ajax, any help greatly appreciated.
http://www.experts-exchange.com/Web/Web_Languages/JavaScript/Q_22062461.html
thanks
0
 
LVL 14

Expert Comment

by:boonleng
Comment Utility
The following is simple code with Ajax and Struts.
In my application, I uses JSON instead of XML as output data and some open source Ajax API to communicate with the server.

struts-config:
      <action path="/sample_ajax"
                  type="sample.web.SampleAction"
                  parameter="ajax"
                  validate="false">
      </action>

Action class:

    public ActionForward execute(ActionMapping mapping,
        ActionForm form,
        HttpServletRequest request,
        HttpServletResponse response) throws Exception {

        response.setContentType("text/xml");
        response.setDateHeader("Expires", 0);
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-store,no-cache,must-revalidate");
        response.addHeader("Cache-Control", "post-check=0,pre-check=0");
       
        PrintWriter out = response.getWriter();
        out.print("<foo>");
        out.print("    <row label='Red Color'>red</row>");
        out.print("    <row label='Blue Color' value='blue'/>");
        out.print("    <row label='Green Color' value='green'/>");
        out.print("</foo>");

        out.close();

        return null;
    }


JSP:

<script>
// initial XMLHttpRequest
var xmlHttpReq = false;

if (window.XMLHttpRequest) {
      xmlHttpReq = new XMLHttpRequest();
      xmlHttpReq.overrideMimeType('text/xml');
} else if (window.ActiveXObject) {
      try {
            xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
      } catch(e) {
            try      {
                  xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(ex) {
                  req = null;
            }
      }
}

function populateData(field1) {
      try {
          var strURL   = '<html:rewrite action="sample_ajax"/>';
          var strParam = 'dropdown1=' + field1.options[field1.selectedIndex].value;

          xmlHttpReq.open('POST', strURL, true);
          xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
          xmlHttpReq.onreadystatechange = function() {
                  if (xmlHttpReq.readyState == 4) {
                        if (xmlHttpReq.status == 200) { // complete
                              var root    = xmlHttpReq.responseXML;
                              var optArry = root.getElementsByTagName('row');

                              var dropdown2 = document.getElementById("dropdown2");
                              for(i=0; i<optArry.length; i++) {
                                    dropdown2.options[i] = new Option(
                                          optArry[i].getAttribute("label"),
                                          optArry[i].getAttribute("label"));
                              }
                              dropdown2.length = optArry.length;
                              dropdown2.selectedIndex = 0;

                        } else {
                              alert("Error accessing URL. code: " + xmlHttpReq.status);
                        }
                  } else if (xmlHttpReq.readyState == 1) { // loading
                  }
            }
            xmlHttpReq.send(strParam);
      } catch (e) {
            alert(e);
      }
}
</script>

<select name="dropdown1" id="dropdown1" onchange="populateData(this)">
      <option value="foo1">foo1</option>
      <option value="foo2">foo2</option>
      <option value="foo3">foo3</option>
</select>
<select name="dropdown2" id="dropdown2">
</select>
0
 
LVL 10

Author Comment

by:jaggernat
Comment Utility
thanks for the sample code boonleng. so i was just trying to understand the flow here.
when user selects something in "dropdown1" ,onChange function :  populateData(field1) is called and if i am right , this function is calling  "<html:rewrite action="sample_ajax"/>"  ,which calls the Action class.
and in action class you have
>>>
 PrintWriter out = response.getWriter();
        out.print("<foo>");
        out.print("    <row label='Red Color'>red</row>");
        out.print("    <row label='Blue Color' value='blue'/>");
        out.print("    <row label='Green Color' value='green'/>");
        out.print("</foo>");

        out.close();
        return null;
>>>
1. what is above code doing in action class? does it return null or does it return javascript to populate the next drop-down,dropdown2.
I was trying to match the sample code to my scenario. I have the xml data (which is generated by a java utility class) in this format
<state>
  <region>
     <county>
         <municipality>
               <hospital>
               </hospital>
         </municipality>
     </county>
  </region>
</state>
for 5 dropdown fields (state,region,county,municipality, hospital ) in that order.

So if i use ajax i will have 4 methods like
populateDataRegion(this),
populateDataCounty(this),
populateDataMuni(this),
populateDataHospital(this),
  **onChange of State drop-down field i call populateDataRegion(this) and likewise for other drop-downs

2. so i am not sure what i should do in my action class mehtod?

3. Would there be difference between the javascript working solution which i have and your ajax solution (performance wise).

thanks a lot boonleng!
J
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 14

Expert Comment

by:boonleng
Comment Utility
>> 1. what is above code doing in action class? does it return null or does it return javascript to populate the next drop-down,dropdown2.
It returns the portion of the XML, and the javascript will read the XML and populate the dropdown.
For exmple, once the user selected a region, the action class will read the generated XML and return the relavent data.
You don't need to return all the nested data such as municipality, hospital to the client. You can also return string with delimter or javascript array, the client side (javascript) just need to handle the pass back data.

out.print("<region name='Europe'>");
out.print("    <county>England</county>");
out.print("    <county>France</county>");
out.print("    <county>Italy</county>");
out.print("</region>");


>> 2. so i am not sure what i should do in my action class mehtod?
The action class should read the generated XML using  XML API such as Excess base on the pass in value from user.


>> 3. Would there be difference between the javascript working solution which i have and your ajax solution (performance wise).
The performance will be better as the amount of data transfer between client and server is very little, you don't need to send all the data to client.

How you generate the XML file?  generate once when server startup or when page loaded?
0
 
LVL 10

Author Comment

by:jaggernat
Comment Utility
i have a  java util class which is generating the xml file using string buffer and i load it in my javascript.on page load the xml is called
0
 
LVL 10

Author Comment

by:jaggernat
Comment Utility
>>>The action class should read the generated XML using  XML API such as Excess base on the pass in value from user.


I am not sure how to do that? do you have any sample code

I have like 50 states, 200 regions, 400 counties, 800 municipalities and 1000 hospitals in my xml.


>>>once the user selected a region, the action ..

once the user selects a region, all the other 3 drop-down below it changes.
this is the structure

state
region
county
municipality
hospital

if state is changed all 4 drop-downs below it are changed.If region is changed, all three drop-down below region is changed (but state remains the same) and so on..

thanks
J
0
 
LVL 14

Expert Comment

by:boonleng
Comment Utility
>> once the user selects a region, all the other 3 drop-down below it changes.

Do you means that when page loaded, you already loaded all the data (50 states, 200 regions, 400 counties, 800 municipalities and 1000 hospitals) into all 5 of the dropdowns, then filter when user change the dropdown option?
0
 
LVL 10

Author Comment

by:jaggernat
Comment Utility
yes , the xml contains all the data when page is loaded. database call is made only once and data is stored in xml
0
 
LVL 14

Accepted Solution

by:
boonleng earned 500 total points
Comment Utility
Since all the data for the dropdowns has been loaded to the client in the XML file, then I don't think the application need to goes back to the server just to filter the data, use javascript to manupilate the data in XML is enought.

Usually in this kind of senario, when the page loaded I will only populate the options for states and leave all others dropdown empty, once the user choose the state, I will use Ajax to retrieve the region options of the selected state. Once region is selected, fetch the countries and so on.. Everytime there's a server call, I will load the data from database instead of XML (If you are using Hibernate, then you can cache the data easily).
Using this way I don't need to load all the unnesessary data, only small amount of the required data is trasmitted between the client and server.



0
 
LVL 10

Author Comment

by:jaggernat
Comment Utility
>>>use javascript to manupilate the data in XML is enought

exactly, that is what i am doing. using xpath in javascript, i am navigating the xml and displaying the drop-downs. so i have decided to keep ajax away from this module since i laready have a working javascript solution and i dont want to revamp the code with ajax.

>>>Using this way I don't need to load all the unnesessary data, only small amount of the required data is trasmitted between the client and server.


actually my architect came up with this current solution and i am caching the data in xml itself without making repeated calls to database. anyway in your scenario you are caching the data in hibernate. so i guess we are both caching the data in different ways :)

thanks a lot for your expert sugessions.
may be i will use ajax for some other module starting from scratch.

thanks
J
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

HOW TO: Connect to the VMware vSphere Hypervisor 6.5 (ESXi 6.5) using the vSphere (HTML5 Web) Host Client 6.5, and perform a simple configuration task of adding a new VMFS 6 datastore.
Restoring deleted objects in Active Directory has been a standard feature in Active Directory for many years, yet some admins may not know what is available.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now