在JSP / Servlet中填充级联下拉列表 [英] Populating cascading dropdown lists in JSP/Servlet

查看:282
本文介绍了在JSP / Servlet中填充级联下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有三个下拉列表控件名为 dd1 dd2 dd3 。每个下拉列表的值来自数据库。 dd3 的值取决于 dd2的价值 dd2 值取决于 dd1 的值。任何人都可以告诉我如何为这个问题调用servlet?

解决方案

基本上有三种实现方法:


  1. 在第一个下拉列表的onchange事件期间将表单提交到一个servlet(可以使用Javascript),让servlet获取选定的作为请求参数的第一个下拉列表的项目,让它从数据库获取第二个下拉列表的相关值作为 Map< String,String> ,让它将它们存储在请求范围最后让JSP / JSTL在第二个下拉菜单中显示值。您可以使用 JSTL (只需删除 jstl-1.2.jar / WEB -INF / lib c:forEach 标签。您可以预先填写与JSP页面关联的 Servlet doGet()方法中的第一个列表。

     < select name =dd1onchange =submit()> 
    < c:forEach items =$ {dd1options}var =option>
    < option value =$ {option.key}$ {param.dd1 == option.key? 'selected':''}> $ {option.value}< / option>
    < / c:forEach>
    < / select>
    < select name =dd2onchange =submit()>
    < c:if test =$ {empty dd2options}>
    < option>请选择父< / option>
    < / c:if>
    < c:forEach items =$ {dd2options}var =option>
    < option value =$ {option.key}$ {param.dd2 == option.key? 'selected':''}> $ {option.value}< / option>
    < / c:forEach>
    < / select>
    < select name =dd3>
    < c:if test =$ {empty dd3options}>
    < option>请选择父< / option>
    < / c:if>
    < c:forEach items =$ {dd3options}var =option>
    < option value =$ {option.key}$ {param.dd3 == option.key? 'selected':''}> $ {option.value}< / option>
    < / c:forEach>
    < / select>

    但是,请注意,这将提交整个表单,并导致Flash内容可能对用户体验不利。您还需要根据请求参数以相同的形式保留其他字段。您还需要在servlet中确定请求是否更新下拉列表(子下拉列表值为null)或提交实际表单。


  2. 将第2和第3个下拉列表中的所有可能值作为Javascript对象打印出来,并使用Javascript函数根据第一个下拉列表中的第一个下拉菜单中的第一个下拉列表项选择第二个下拉列表。没有表单提交,这里不需要服务器周期。

     < script> 
    var dd2options = $ {dd2optionsAsJSObject};
    var dd3options = $ {dd3optionsAsJSObject};
    函数dd1change(dd1){
    //根据选择的dd1值填充dd2选项。
    var selected = dd1.options [dd1.selectedIndex] .value;
    ...
    }
    函数dd2change(dd2){
    //根据选定的dd2值填充dd3选项。
    var selected = dd2.options [dd2.selectedIndex] .value;
    ...
    }
    < / script>

    < select name =dd1onchange =dd1change(this)>
    < c:forEach items =$ {dd1options}var =option>
    < option value =$ {option.key}$ {param.dd1 == option.key? 'selected':''}> $ {option.value}< / option>
    < / c:forEach>
    < / select>
    < select name =dd2onchange =dd2change(this)>
    < option>请选择父< / option>
    < / select>
    < select name =dd3>
    < option>请选择父< / option>
    < / select>

    但是,当您有很多很多时,这可能会变得不必要的冗长和昂贵/ strong>的项目。想象一下,每100个可能的项目有3个步骤,这意味着JS对象中的100 * 100 * 100 = 1,000,000个项目。 HTML页面的长度将超过1MB。


  3. 在第一个下拉列表的onchange事件期间,使用Javascript中的XMLHttpRequest来触发对servlet的异步请求,让servlet将第一个下拉列表的选定项目作为请求参数,让它从数据库中获取第二个下拉列表的相关值,将其作为XML返回或 JSON 字符串。最后让Javascript通过HTML DOM树在第二个下拉列表中显示值(Ajax方式,如前所述)。最好的方法是使用 jQuery

     <%@ page pageEncoding =UTF-8%> 
    <%@ taglib uri =http://java.sun.com/jsp/jstl/coreprefix =c%>
    <!DOCTYPE html>
    < html lang =en>
    < head>
    < title> SO question 2263996< / title>
    < script src =http://code.jquery.com/jquery-latest.min.js>< / script>
    < script>
    $(document).ready(function(){
    $('#dd1')。change(function(){fillOptions('dd2',this);});
    $ ('#dd2')。change(function(){fillOptions('dd3',this);});
    });
    函数fillOptions(ddId,callingElement){
    var dd = $('#'+ ddId);
    $ .getJSON('json / options?dd ='+ ddId +'& val ='+ $(callingElement).val(),function(opts){
    $('> ',dd).remove(); //首先清除旧选项
    if(opts){
    $ .each(opts,function(key,value){
    dd.append $('< option />')。val(key).text(value));
    });
    } else {
    dd.append($('选项/>')。text(请选择父));
    }
    });
    }
    < / script>
    < / head>
    < body>
    < form>
    < select id =dd1name =dd1>
    < c:forEach items =$ {dd1}var =option>
    < option value =$ {option.key}$ {param.dd1 == option.key? 'selected':''}> $ {option.value}< / option>
    < / c:forEach>
    < / select>
    < select id =dd2name =dd2>
    < option>请选择父< / option>
    < / select>
    < select id =dd3name =dd3>
    < option>请选择父< / option>
    < / select>
    < / form>
    < / body>
    < / html>

    ..其中 Servlet c $ c> / json / options 可以这样:

      protected void doGet(HttpServletRequest request ,HttpServletResponse响应)throws ServletException,IOException {
    String dd = request.getParameter(dd); //为了填充DD的子代码的ID。
    String val = request.getParameter(val); //父DD的值查找相关联的子DD选项。
    映射< String,String> options = optionDAO.find(dd,val);
    String json = new Gson()。toJson(options);
    response.setContentType(application / json);
    response.setCharacterEncoding(UTF-8);
    response.getWriter()。write(json);
    }

    这里, Gson Google Gson ,它可以将完整的Java对象转换为JSON,反之亦然。另请参见如何使用Servlet和Ajax?



Suppose I am having three dropdownlist controls named dd1, dd2 and dd3. The value of each dropdownlist comes from database. dd3's value depends upon value of dd2 and dd2's value depends on value of dd1. Can anyone tell me how do I call servlet for this problem?

解决方案

There are basically three ways to achieve this:

  1. Submit form to a servlet during the onchange event of the 1st dropdown (you can use Javascript for this), let the servlet get the selected item of the 1st dropdown as request parameter, let it obtain the associated values of the 2nd dropdown from the database as a Map<String, String>, let it store them in the request scope. Finally let JSP/JSTL display the values in the 2nd dropdown. You can use JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) c:forEach tag for this. You can prepopulate the 1st list in the doGet() method of the Servlet associated with the JSP page.

    <select name="dd1" onchange="submit()">
        <c:forEach items="${dd1options}" var="option">
            <option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option>
        </c:forEach>
    </select>
    <select name="dd2" onchange="submit()">
        <c:if test="${empty dd2options}">
            <option>Please select parent</option>
        </c:if>
        <c:forEach items="${dd2options}" var="option">
            <option value="${option.key}" ${param.dd2 == option.key ? 'selected' : ''}>${option.value}</option>
        </c:forEach>
    </select>
    <select name="dd3">
        <c:if test="${empty dd3options}">
            <option>Please select parent</option>
        </c:if>
        <c:forEach items="${dd3options}" var="option">
            <option value="${option.key}" ${param.dd3 == option.key ? 'selected' : ''}>${option.value}</option>
        </c:forEach>
    </select>
    

    Once caveat is however that this will submit the entire form and cause a "flash of content" which may be bad for User Experience. You'll also need to retain the other fields in the same form based on the request parameters. You'll also need to determine in the servlet whether the request is to update a dropdown (child dropdown value is null) or to submit the actual form.

  2. Print all possible values of the 2nd and 3rd dropdown out as a Javascript object and make use of a Javascript function to fill the 2nd dropdown based on the selected item of the 1st dropdown during the onchange event of the 1st dropdown. No form submit and no server cycle is needed here.

    <script>
        var dd2options = ${dd2optionsAsJSObject};
        var dd3options = ${dd3optionsAsJSObject};
        function dd1change(dd1) {
            // Fill dd2 options based on selected dd1 value.
            var selected = dd1.options[dd1.selectedIndex].value;
            ...
        }
        function dd2change(dd2) {
            // Fill dd3 options based on selected dd2 value.
            var selected = dd2.options[dd2.selectedIndex].value;
            ...
        }
    </script>
    
    <select name="dd1" onchange="dd1change(this)">
        <c:forEach items="${dd1options}" var="option">
            <option value="${option.key}" ${param.dd1 == option.key ? 'selected' : ''}>${option.value}</option>
        </c:forEach>
    </select>
    <select name="dd2" onchange="dd2change(this)">
        <option>Please select parent</option>
    </select>
    <select name="dd3">
        <option>Please select parent</option>
    </select>
    

    One caveat is however that this may become unnecessarily lengthy and expensive when you have a lot of items. Imagine that you have 3 steps of each 100 possible items, that would mean 100 * 100 * 100 = 1,000,000 items in JS objects. The HTML page would grow over 1MB in length.

  3. Make use of XMLHttpRequest in Javascript to fire an asynchronous request to a servlet during the onchange event of the 1st dropdown, let the servlet get the selected item of the 1st dropdown as request parameter, let it obtain the associated values of the 2nd dropdown from the database, return it back as XML or JSON string. Finally let Javascript display the values in the 2nd dropdown through the HTML DOM tree (the Ajax way, as suggested before). The best way for this would be using jQuery.

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

    ..where the Servlet behind /json/options can look like this:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String dd = request.getParameter("dd"); // 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 = optionDAO.find(dd, val);
        String json = new Gson().toJson(options);
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }
    

    Here, Gson is Google Gson which eases converting fullworthy Java objects to JSON and vice versa. See also How to use Servlets and Ajax?

这篇关于在JSP / Servlet中填充级联下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆