Just sharing the code/process to generate chain selector/cascading/dynamic dropdown using JSP/Servlet and AJAX. It might be helpful for peoples trying to implement this functionality.
Overview of my example
We have two tables in DB - Country and City.
Country has two columns - countryid and countryname
City has two column - cityid and cityname
we have requirement to create two dropdowns (one displaying all Country names and second one displaying city names corresponding to Country being selected in first dropdown ) on JSP page.
Functionality required is that - user select County name in first dropdown. Content of second dropdown should automatically populate corresponding list of cities that belongs to the Country selected.
here is the code
a. Create a jsp with first dropdown and code as shown below. Also include below shown ajax code in this jsp
Here is the ajax script that will fetch second dropdown from FetchCity servlet
Now in fetchCites servlet , in doGet()/doPost() method, call DB query (using JDBC/ Hibernate/any other ORM framework) to fetch all cities corresponding to country selected (countryid).
after that , prepare second dropwdown within servlet using out.println().
foreg - code generated for England selected as country.
this code will be placed on browser within second_dropdown_code div.