使用 JSP、Servlet、JQuery 和非规范化 Mysql 表的依赖动态下拉列表

Posted

技术标签:

【中文标题】使用 JSP、Servlet、JQuery 和非规范化 Mysql 表的依赖动态下拉列表【英文标题】:Dependent dynamic dropdown using JSP, Servlet, JQuery and denormalized Mysql table 【发布时间】:2018-10-14 06:42:45 【问题描述】:

请查看下面显示的示例非规范化数据库:

|----|---------------|---------|------------------------|---------------|----------------------|
| id | continent     | country | state                  | city          | street               |
|----|---------------|---------|------------------------|---------------|----------------------|
| 1  | North America | USA     | California             | San Francisco | Broadway             |
| 2  | South America | Brazil  | Sao Paulo              | Campinas      | R. Dr. Emilio Ribas  |
| 3  | South America | Brazil  | Sao Paulo              | Campinas      | R. Dr. Vieira Bueno  |
| 4  | Asia          | India   | Maharashtra            | Mumbai        | C.S.                 |
| 5  | Asia          | India   | Maharashtra            | Mumbai        | S.V.                 |
| 7  | Europe        | Germany | North Rhine-Westphalia | Duisburg      | Essenberger          |
| 8  | Europe        | Germany | North Rhine-Westphalia | Bochum        | Solingen             |
| 9  | Europe        | France  | Lorraine               | Toul          | Dijon                |
| 10 | Europe        | France  | Lorraine               | Verdun        | 50 Avenue            |
| 11 | North America | USA     | Massachusetts          | Boston        | Saint Alphonsus      |
| 12 | North America | Canada  | Ontario                | Kingston      | 1st Avenue           |
| 13 | North America | Canada  | Ontario                | Kingston      | 7th Avenue           |
| 14 | North America | Canada  | British Columbia       | Kamloops      | Albert               |
| 15 | North America | USA     | Massachusetts          | Boston        | Eliot                |
|----|---------------|---------|------------------------|---------------|----------------------|

每个下拉列表的值来自上面显示的数据库。街道的价值取决于城市的价值,城市的价值取决于州的价值,州的价值取决于国家的价值,国家的价值取决于大陆的价值。

例如:如果我选择北美作为大陆,则国家/地区的下拉菜单应仅显示美国和加拿大。接下来,如果我选择 USA,则 State 的下拉菜单应仅显示 California 和 Massachusetts 等。当使用 jquery/JSP/Servlet 对数据库进行非规范化时,谁能帮我实现解决方案?

到目前为止,我已经完成了以下编码。我用过jquery,写了一个jsp:

<%@ page pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Dependent Dropdown</title>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script>
            $(document).ready(function() 
                $('#continent').change(function()  fillOptions('country', this); );
                $('#country').change(function()  fillOptions('state', this); );
                $('#state').change(function()  fillOptions('city', this); );
                $('#city').change(function()  fillOptions('street', this); );
            );
            function fillOptions(childID, parentID) 
                var child = $('#' + childID);
                $.getJSON('json/options?child=' + childID + '&val=' + $(parentID).val(), function(opts) 
                    $('>option', child).remove(); // Clean old options first.
                    if (opts) 
                        $.each(opts, function(key, value) 
                            child.append($('<option/>').val(key).text(value));
                        );
                     else 
                        child.append($('<option/>').text("Please select parent"));
                    
                );
            
        </script>
    </head>
    <body>
        <form>
            <select id="continent" name="continent">
                <c:forEach items="$continent" var="option">
                    <option value="$option.key" $param.continent == option.key ? 'selected' : ''>$option.value</option>
                </c:forEach>
            </select>
            <select id="country" name="country">
                <option>Please select parent</option>
            </select>
            <select id="state" name="state">
                <option>Please select parent</option>
            </select>
            <select id="city" name="city">
                <option>Please select parent</option>
            </select>
            <select id="street" name="street">
                <option>Please select parent</option>
            </select>
        </form>
    </body>
</html>

/json/options 后面的Servlet 看起来像:

import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import com.google.gson.Gson;
import com.amey.dao.AddressDAO;
import com.amey.dao.AddressDAOImplementation;

@WebServlet("/CascadingDropdownController")
public class CascadingDropdownController extends HttpServlet 
    private static final Logger LOG = Logger.getLogger( CascadingDropdownController.class.getName() );
    private AddressDAO dao;
    private static final long serialVersionUID = 1L;

    public CascadingDropdownController() 
            dao = new AddressDAOImplementation();
    

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
        LOG.info("In doGet ");
        String child = request.getParameter("child"); // ID of child DD to fill options for.
        String val = request.getParameter("val"); // Value of parent DD to find associated child DD options for.
        Map<String, String> options = null;
        try 
            options = dao.find(child, val);
         catch (Exception e) 
            // TODO Auto-generated catch block
            e.printStackTrace();
        
        String json = new Gson().toJson(options);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    

老实说,我不清楚 DAO 的实施。我需要有关 DAO 逻辑的帮助。

【问题讨论】:

【参考方案1】:

不同的大陆列表:

 SELECT t.continent
   FROM mysqltable t
  GROUP
     BY t.continent

给定大陆的不同国家/地区列表:

 SELECT t.country
   FROM mysqltable t
  WHERE t.continent = 'North America'
  GROUP
     BY t.continent
      , t.country

给定大陆和国家的不同州列表:

 SELECT t.state
   FROM mysqltable t
  WHERE t.continent = 'North America'
    AND t.country   = 'Canada'
  GROUP
     BY t.continent
      , t.country
      , t.state

【讨论】:

以上是关于使用 JSP、Servlet、JQuery 和非规范化 Mysql 表的依赖动态下拉列表的主要内容,如果未能解决你的问题,请参考以下文章

Jsp +Js + Jquery + EasyUI + Servlet + Lucene,完成分页

使用JSP/Servlet技术开发—— 第十一章 Ajax交互扩展

jquery直接显示jsp返回的数据

基于三层架构+java+jsp+servlet+jQuery+bootstrap——web资源库项目(注册功能demo)

基于Tomcat服务器,通过JQuery的Ajax方法访问Servlet实现前后端数据同步/异步交流(不必跳转或者刷新网页实现JSP前后端交互)

基于Tomcat服务器,通过JQuery的Ajax方法访问Servlet实现前后端数据同步/异步交流(不必跳转或者刷新网页实现JSP前后端交互)