简体   繁体   中英

Loading a list from database on selection of value from another list

I have 2 drop down lists in my web page.A Country List and Province List. When page loads, my country list is populated from data base and then on selection of a country from the list, the province list of that country should be populated also from the database.

(I am using hibernate reverse engineering for creating database connection files and bean classes etc)

What i am doing is after populating the country list, i get the value of the country selected using jquery script then pass it via a url using ajax to the controller class. Which i will attach below.

The problem i face is when i select a country from the country list, instead of populating the province list the two dropdown boxes are printed again and the province list box remains empty.

Here is my jsp file

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Selection Page</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>

</head>
<body>
    <form name="locationSelection" method="POST">

    Select Country:
        <br>
        <select name="countryList" id="countryList">
            <option value="">Select Country</option>
            <c:if test="${!empty countryList}">
                <c:forEach items="${countryList}" var="cont">
                    <option   value=${cont.countryId}>${cont.countryName}</option>
                </c:forEach>
            </c:if>
        </select>
        <br><br>

        <script>
        $(document).ready(function() 
        {
            $("#countryList").change(function() 
            {
                var selectedValue = $(this).find(":selected").val();
                $.ajax
                ({
                    url : "a.html?cID="+selectedValue+'',
                    success : function(result) 
                    {
                        $("#prvContatiner").html(result);
                    }
                });
            });
        });
        </script>

        Select Province:
        <div id="prvContatiner">
            <select name="provinceList" id="provinceList">
                <option value="">Select Province</option>
                      <c:if test="${!empty provinceList}">
                <c:forEach items="${provinceList}" var="cont">
                    <option   value=${cont.provinceId}>${cont.provinceDesc}</option>
                </c:forEach>
            </c:if>
        </select> 
            </select>
        </div>

    </form>
</body>

and here is my controller java class

package controller;

import java.io.IOException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.TblCountryDAO;
import dao.TblProvinceDAO;

@SuppressWarnings("serial")
public class SelectionController extends HttpServlet {
    void ProcessorRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        String operation = request.getParameter("op");
        System.out.println("Operation: "+operation);
        String cID = request.getParameter("cId");
        if (cID == null) 
        {
            System.out.println(request.getRequestURI());
            TblCountryDAO dao = new TblCountryDAO();
            List<?> countryList = dao.findAll();
            request.setAttribute("countryList", countryList);
            RequestDispatcher reqDispatcher = request.getRequestDispatcher("main.jsp");
            reqDispatcher.forward(request, response);
        }
        else 
        {
            System.out.println("in elseif");

            TblProvinceDAO dao = new TblProvinceDAO();
            List<?> provinceList = dao.findByProperty("tblCountry.countryId", Integer.parseInt(cID));
            request.setAttribute("provinceList", provinceList);
            RequestDispatcher reqDispatcher = request.getRequestDispatcher("main.jsp");
            reqDispatcher.forward(request, response);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
        ProcessorRequest(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
        ProcessorRequest(req, resp);
    }
}

I am attaching the web.xml file just in case

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name></display-name>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>controller.SelectionController</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/a.html</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Any other suggestion for doing the task will also be greatly appreciated

you are looking for wrong parameter request.getParameter("cId"); should be request.getParameter("cID"); using cId will return you null value and you will get main.jsp in response

I think you can switch to an another way to accomplish the same task with the help of json

in the controller you are getting the list of province. Use any of Json library such as google gson or json.org and convert it into json array of object like this

[{
"id":1,
"name":"Delhi"
},{
...
...
},
...
]

and directly print the json array using PrintWriter.

and then in your ajax success response generate the options like this -

$.ajax
                ({
                    url : "a.html?cID="+selectedValue+'',
                    success : function(result) 
                    {
                        $("#provinceList").html('');
                        for(var i=0;i<result.size;i++){
                            var option = '<option value="'+result[i].id+'">'+result[i].name+'</option>'
                            $("#provinceList").append(option);
                        }
                    }
                });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM