Open In App

Dynamic Dropdown From Database using Spring Boot

The concept of dynamic dropdown (or dependent dropdown) is exciting and challenging to code. Dynamic dropdown means that the values in one dropdown list are dependent on the value selected in the previous dropdown list. A simple example would be three dropdown boxes displaying names of the district, taluk, and village where the values in taluk depend on the value selected in the district, and the values in the village depend on the value selected in the taluk dropdown. Dynamic Dropdown can be implemented using the following technologies:

  1. Any database can be used to load the details of the districts, taluks, and villages that are to be populated in the dropdown. In this case, we will be using PostgreSQL.
  2. Service class to connect to the database can be implemented using Java and Spring Boot.
  3. HTML, CSS, JavaScript, jQuery, and AJAX can be used to implement the dropdown lists.

The best approach for this tutorial would be to start with creating and populating the databases first, coding the Java service class next, and then proceeding to design and code the dropdown lists in the webpage. It would also be helpful to visualize the approximate output of this tutorial before proceeding further.



DISTRICT SELECTED

TALUK SELECTED

VILLAGE SELECTED

Now that the output has been visualized, it’s time to narrow down the details for executing the objective of this tutorial. It is recommended to create the Spring Boot project separately and the web pages separately in another project.



Project 1 for Service Method:

The procedure to create a Spring Boot project is explained in the following tutorial: Spring Boot – Service Class Example for Displaying Response Codes and Custom Error Codes. The database part consists of one CREATE command for each table, some INSERT commands for each table. The create commands and the corresponding insert commands for the tables are listed below:

CREATE TABLE district (id int SERIAL PRIMARY KEY,name varchar(50),distcode varchar(4));
insert into district (name,distcode) values('Chennai','1');
insert into district (name,distcode) values('Coimbatore','2');
CREATE TABLE taluk (id int SERIAL PRIMARY KEY,name varchar(50),distcode varchar(4),talukcode varchar(4));
insert into taluk (name,distcode,talukcode) values('Avadi','1','12');
insert into taluk (name,distcode,talukcode) values('Sulur','2','3');
CREATE TABLE village (id int SERIAL PRIMARY KEY,name varchar(50),distcode varchar(4),talukcode varchar(4),villagecode varchar(4));
insert into village (name,distcode,talukcode,villagecode) values('Pothur','1','12','15');
insert into village (name,distcode,talukcode,villagecode) values('Arasur','2','10','9');

The images of the respective databases are shown below:

DISTRICT DATABASE

TALUK DATABASE

VILLAGE DATABASE

DBController.java




package com.springboot.springbootdemo;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.websocket.server.PathParam;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
@CrossOrigin
public class DBController {
 
    PreparedStatement ps;
    Connection con;
    String sql;
 
    @GetMapping("/dist")
    @CrossOrigin
    public String saylistDistrict() throws SQLException
    {
          PreparedStatement ps;
        ResultSet myRs;
        JSONArray districtlist = new JSONArray();
        try {
            Class.forName("org.postgresql.Driver");
            con = DriverManager.getConnection(
                "jdbc:postgresql://localhost:5432/test?allowPublicKeyRetrieval=true",
                "postgres", "password");
            sql = "SELECT distcode, name FROM district";
            ps = con.prepareStatement(sql);
            myRs = ps.executeQuery();
            while (myRs.next()) {
                JSONObject jsonobj = new JSONObject();
                jsonobj.put("districtcode",
                            myRs.getString("distcode")
                                .toString()
                                .trim());
                jsonobj.put("districtname",
                            myRs.getString("name")
                                .toString()
                                .trim());
                districtlist.add(jsonobj);
            }
            System.out.println("districtlist"
                               + districtlist.size());
            close(con, ps, myRs);
        }
        catch (Exception e) {
            System.out.println("getservice Exception==>"
                               + e);
        }
 
        return (districtlist.toString());
    }
 
    @RequestMapping(value = "/taluk",
                    method = RequestMethod.GET)
    @ResponseBody
    @CrossOrigin
    public String
    ListTaluk(@RequestParam String Discode)
        throws ParseException
    {
          String districtcode = Discode;
        JSONArray taluklist = new JSONArray();
        try {
            Class.forName("org.postgresql.Driver");
            con = DriverManager.getConnection(
                "jdbc:postgresql://localhost:5432/test?allowPublicKeyRetrieval=true",
                "postgres", "password");
            sql = " select * from taluk where distcode=?";
            ps = con.prepareStatement(sql);
              ps.setString(1, districtcode);
            ResultSet res = ps.executeQuery();
            while (res.next()) {
                JSONObject jsontaluk = new JSONObject();
                jsontaluk.put("districtcode",
                              res.getString("distcode")
                                  .toString()
                                  .trim());
                jsontaluk.put("talukcode",
                              res.getString("talukcode")
                                  .toString()
                                  .trim());
                jsontaluk.put("talukname",
                              res.getString("name")
                                  .toString()
                                  .trim());
                taluklist.add(jsontaluk);
            }
            System.out.println("taluklist"
                               + taluklist.size());
            close(con, ps, res);
        }
        catch (Exception e) {
            System.out.println(
                "getservice Edistid1xception==>" + e);
        }
        return (taluklist.toString());
    }
 
    @RequestMapping(value = "/village",
                    method = RequestMethod.GET)
    @ResponseBody
    @CrossOrigin
    public String
    Listvillage(@RequestParam String Discode,
                @RequestParam String Talukcode)
        throws ParseException
    {
        String districtcode = Discode;
        String talukcode = Talukcode;
        JSONArray villagelist = new JSONArray();
        try {
            Class.forName("org.postgresql.Driver");
            con = DriverManager.getConnection(
                "jdbc:postgresql://localhost:5432/test?allowPublicKeyRetrieval=true",
                "postgres", "password");
            sql = "select * from village where distcode=? and talukcode=?";
            ps = con.prepareStatement(sql);
              ps.setString(1, districtcode);
            ps.setString(2, talukcode);
            ResultSet resl = ps.executeQuery();
 
            while (resl.next()) {
                JSONObject jsonvillage = new JSONObject();
                jsonvillage.put("districtcode",
                                resl.getString("distcode")
                                    .toString()
                                    .trim());
                jsonvillage.put("talukcode",
                                resl.getString("talukcode")
                                    .toString()
                                    .trim());
                jsonvillage.put(
                    "villagecode",
                    resl.getString("villagecode")
                        .toString()
                        .trim());
                jsonvillage.put("villagename",
                                resl.getString("name")
                                    .toString()
                                    .trim());
                villagelist.add(jsonvillage);
            }
            System.out.println("villagelist"
                               + villagelist.size());
            close(con, ps, resl);
        }
        catch (Exception e) {
            System.out.println("getservice Exception==>"
                               + e);
        }
        return (villagelist.toString());
    }
 
    private static void close(Connection myConn,
                              Statement myStmt,
                              ResultSet myRs)
    {
        try {
            if (myRs != null) {
                myRs.close();
            }
            if (myStmt != null) {
                myStmt.close();
            }
            if (myConn != null) {
                myConn.close();
            }
        }
        catch (Exception exc) {
            exc.printStackTrace();
        }
    }
}

The explanation for the above code:

Note: It’s important to close the database connection each time after usage in a web application. Failing to do so might result in memory leakage, performance slowdown, connection shortage when a user requests for a database connection from the database server.

Project 2 for webpage and front-end

dropdown.jsp




<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<script  type="text/javascript" src="jquery-3.6.0.min.js"></script>
<script  type="text/javascript" src="Ajaxcall.js"></script>
<!DOCTYPE html>
<html>
   <head>
      <meta charset="ISO-8859-1">
      <title>Insert title here</title>
   </head>
   <body>
      <table border="1" cellpadding="10px" cellspacing="5px">
         <tr>
            <td>District: </td>
            <td>
               <select id="districtlist" name="districtlist" required>
                  <option disabled selected>Select District</option>
               </select>
            </td>
         </tr>
         <tr>
            <td>Taluk: </td>
            <td>
               <select id="taluklist" name="taluklist" required>
                  <option disabled>Select Taluk</option>
               </select>
            </td>
         </tr>
           
         <tr>
            <td>Village: </td>
            <td>
               <select id="villagelist" name="villagelist" required>
                  <option disabled>Select Village</option>
               </select>
            </td>
         </tr>
      </table>
   </body>
</html>

The plugin jquery-3.6.0.min.js needs to be imported into the HTML project and it works best when the plugin is deployed in the local project and imported. The webpage is plain only with a basic layout and not much CSS since the scope of this tutorial is only to explain dynamic dropdown based on the database. Now that the webpage layout for the dropdowns has been coded, it’s time to write the AJAX calls. A JavaScript file called Ajaxcall.js is used to populate the dropdown lists. It is also the place where the URL linked to the Java service methods is called.

Ajaxcall.js




var dis;
var tal;
var vill;
$(document).ready(function () {
   $.ajax({
      type: "GET",
      url: "http://localhost:8075/dist",
      data: "json",
      contentType: "application/json",
      success: function (data) {
         let obj = $.parseJSON(data);
         $.each(obj, function (key, value) {
            $('#districtlist').append('<option value="' + value.districtcode + '">' + value.districtcode + '--' + value.districtname + '</option>');
         });
      },
 
      error: function (data) {
         $('#districtlist').append('<option>District Unavailable</option>');
      },
   });
 
   /*$('#districtlist').trigger("change");*/
 
   $('#districtlist').change(function () {
 
      $('#taluklist').find('option').remove();
      $('#taluklist').append('<option>Select taluk</option>');
      $('#villagelist').find('option').remove();
      $('#villagelist').append('<option>Select village</option>');
 
      var distid1 = $('#districtlist').val();
      var inputValObj = {};
      alert(distid1);
      inputValObj.Discode = distid1;
      var inputVal = JSON.stringify(inputValObj);
      alert(inputVal);
      var data = inputVal.toString();
      alert(data);
 
      $.ajax({
         type: "GET",
         url: "http://localhost:8075/taluk?Discode=" + distid1,
         /*data: 1,*/
         contentType: "application/json",
         success: function (data) {
            let obj = $.parseJSON(data);
            $.each(obj, function (key, value) {
               $('#taluklist').append('<option value="' + value.talukcode + '">' + value.talukcode + '--' + value.talukname + '</option>');
            });
         },
         error: function (data) {
            $('#taluklist').append('<option>Taluk Unavailable</option>');
         },
      });
   });
   $('#taluklist').change(function () {
      $('#villagelist').find('option').remove();
      $('#villagelist').append('<option>Select village</option>');
      var distid1 = $('#districtlist').val();
      var talukid = $('#taluklist').val();
      alert(distid1);
      alert(talukid);
      var inputValObj = {};
      inputValObj.Discode = distid1;
      inputValObj.talucode = talukid;
      var inputVal = JSON.stringify(inputValObj);
      var data = inputVal.toString();
      $.ajax({
         type: "GET", //POST  
         url: "http://localhost:8075/village?Discode=" + distid1 + "&" + "Talukcode=" + talukid,
         contentType: "application/json",
         success: function (data) {
            let obj = $.parseJSON(data);
            $.each(obj, function (key, value) {
               $('#villagelist').append('<option value="' + value.villagecode + '">' + value.villagecode + '--' + value.villagename + '</option>');
            });
         },
         error: function (data) {
            $('#villagelist').append('<option>village Unavailable</option>');
         },
      });
   });
});

When the document is ready, the saylistDistrict() function is invoked in the first AJAX call using the “http://localhost:8075/dist” URL and the extracted data goes into the success function. Now, the data is parsed and stored into a variable ‘obj’, then iterated using $.each in jQuery. Each entry in the iteration is then appended into the district dropdown list using the ‘$(‘#districtlist’).append(‘<option value=”‘ + value.districtcode+ ‘”>’ + value.districtcode + ‘–‘ + value.districtname+ ‘</option>’);’ command.

Note: ‘districtlist’ is the ID of the district dropdown.

When the district dropdown is changed, the jQuery ‘$(‘#districtlist’).change(function () {}); is invoked and the url “http://localhost:8075/taluk?Discode=”+distid1 invokes the Java function ListTaluk(). The returned data is then populated in the taluk dropdown using the ‘ $(‘#taluklist’).append(‘<option value=”‘ + value.talukcode + ‘”>’ + value.talukcode + ‘–‘ + value.talukname+ ‘</option>’);’ command.

The jQuery ‘$(‘#taluklist’).change(function () {});’ is invoked when the taluk dropdown value is changed. The url “http://localhost:8075/village?Discode=”+distid1+”&”+”Talukcode=”+talukid invokes the Java function Listvillage(). The returned data is then populated in the ‘villagelist’ dropdown using the ‘$(‘#villagelist’).append(‘<option value=”‘ + value.villagecode + ‘”>’ + value.villagecode + ‘–‘ + value.villagename+ ‘</option>’)’ command.

Additionally, whenever a dropdown is modified, the other dropdown values dependent on the modified dropdown are removed and the “Select” placeholder is inserted. The dropdown values are removed using the .remove() function as demonstrated in the above examples and “Select” placeholder is inserted with commands in the following template “$(‘#taluklist’).append(‘<option>Select taluk</option>’);”.

In any Spring Boot project, there will be a Java class with the @SpringBootApplication annotation which has to be run using right click and Run As _> Java application. The first project has to be run in this way. The second project must be run on the server using right click -Run as -> Run on the server. After the dropdown.jsp has been run using the following method, the output of this tutorial can be observed.


Article Tags :