Solved

struts drop-down

Posted on 2006-11-07
13
1,922 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
ID: 17895814
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
ID: 17899675
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
ID: 17924194
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
ID: 17956065
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
ID: 17970610
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
ID: 17971967
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 14

Expert Comment

by:boonleng
ID: 17976593
>> 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
ID: 17976602
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
ID: 17976635
>>>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
ID: 17977374
>> 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
ID: 17981595
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
ID: 17985013
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
ID: 18000479
>>>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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Microsoft Office Picture Manager was included in Office 2003, 2007, and 2010, but not in Office 2013. Users had hopes that it would be in Office 2016/Office 365, but it is not. Fortunately, the same zero-cost technique that works to install it with …
Note: This is the third blog post in a series on email clearinghouses (https://www.xmatters.com/alert-management/blog-email-has-failed-us?utm_campaign=70138000000ydLoAAI&utm_source=exex&utm_medium=article&utm_content=blog-post).   We’ve been talki…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

932 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

12 Experts available now in Live!

Get 1:1 Help Now