Last Updated on 07 November 2019   |   Print Email
Showing a list of country for the user to select is a very common requirement. But it’s very difficult, time-consuming and inaccurate if you write code manually. It’s even painful if you copy and paste the code of country list from somewhere because the list is very long.So in this post, you will learn a quick, simple and best way to generate a list of all countries in the world and show it in a dropdown list in a webpage that looks like this:Follow the steps below to code a dropdown list of countries with Java Servlet and JSP.
1. Get a list of countries and regions
We take advantage of the Internationalization (i18n) API in Java to get an ISO-standard list of countries and regions. Consider this example program:
package net.codejava;
import java.util.Locale;
public class CountryList {
public static void main(String[] args) {
String[] countryCodes = Locale.getISOCountries();
System.out.println("Number of countries and regions: " + countryCodes.length);
for (String countryCode : countryCodes) {
Locale locale = new Locale("", countryCode);
String code = locale.getCountry();
String name = locale.getDisplayCountry();
System.out.printf("[%s] %s\n", code, name);
}
}
}
Run this program and it will print a list of 250 countries and regions (country code in the brackets) as below:
Number of countries and regions: 250
[AD] Andorra
[AE] United Arab Emirates
[AF] Afghanistan
[AG] Antigua and Barbuda
...
[IL] Israel
[IM] Isle Of Man
[IN] India
[IO] British Indian Ocean Territory
...
[ZA] South Africa
[ZM] Zambia
[ZW] Zimbabwe
Based on this information, we can write code for displaying a list of countries in a webpage with Java Servlet and JSP. Note that this list is sorted by country code.
2. Code to get country list on the server side – Java Servlet
Let’s look at the code of this Java servlet class:
As you can see in the doGet() method, it creates a TreeMap to store the list of countries in alphabetic order of country name (because the raw country list is sorted by code).And the Map object is stored as an attribute in the HttpServletRequest object so it will be available to use used in the forwarded JSP page.
3. Code to display country list on the client side - JSP
In the JSP page, we use forEach tag of JSTL mixed with HTML code to show the dropdown list of countries. For example:
Here, we use country code as value for the <option> tag, and country name as the displayed text.When running, the generated HTML code for the country list looks like this:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments