【问题标题】:JSP listbox and ServletJSP 列表框和 Servlet
【发布时间】:2011-05-22 03:44:14
【问题描述】:

在我的应用程序中,我正在使用 2 个列表框,我想将选定的项目从一个移动到另一个。我知道从数据库中为列表框赋值。但我不知道如何将字符串数组值从 java 文件分配给 html 字段。在我的“record.java”中,我有以下代码:

public class Report 
{
    private static String[] types = {
        "Value1",
        "Value2"
    };

    private static String[] fields = {
        "number1",
        "number2"
    };

    public static String[] getList() {
        return types;
    }

    public static String getFieldName(String description) {
        for(int i=0; i< fields.length; i++) {
            if (description.compareToIgnoreCase(types[i]) ==0)
                return fields[i];
        }
        return "";
    }
}

我的“chart.jsp”文件如下:

<form  method="post">
            <fieldset>
                <legend>Chart Data</legend>
                <br/>
                <br/>
                <table >
                    <tbody>
                        <tr>
                            <td>
                              <select name="data" size="5" id="s">
                                 <option value=""></option>
                              </select>
                            </td>
                            <td> 
                                <input type="submit" value="<<"/>
                            </td>
                            <td>
                                <select name="data" size="5" id="d">
                                 <option value=""></option>
                                </select></td>
                         </tr>
                    </tbody>
                </table>
                <br/>
            </fieldset>
            <input class="submit" type="submit" value="Submit" />
        </form>

我是 JSP 的新手。任何人都可以帮助我如何做到这一点? 谢谢……

【问题讨论】:

    标签: jsp servlets


    【解决方案1】:

    getter 方法不应该是静态的:

    public String[] getList() {
        return types;
    }
    

    Report 的实例应放在 servlet 的 doGet() 方法的请求范围内:

    Report report = loadItSomehow();
    request.setAttribute("report", report);
    request.getRequestDispatcher("page.jsp").forward(request, response);
    

    这样,它将在 JSP EL 中以${report} 的形式提供,而列表以${report.list} 的形式提供。您可以使用 JSTL c:forEach 遍历数组或 List

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    ...
    <select name="types" size="5">
        <c:forEach items="${report.list}" var="type">
            <option value="${type}">${type}</option>
        </c:forEach>
    </select>
    

    请注意,您不应为独立的输入元素赋予相同的名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多