如何使用java servlet在下拉列表中添加数组值

时间:2014-09-05 07:08:17

标签: java jsp servlets

朋友们请告诉我们如何使用java servlet在下拉列表中添加数组值列表。

请检查以下代码并告知此代码中的任何错误..

我的Jsp页面...... DropDown.jsp

<body onload="callAction()">
<form>
<script type="text/javascript">
    function callAction() {
        document.location.href="http://localhost:8084/Servlet/DropDown";
    }
</script>

<select name="Day"><option>Day</option>
    <c:forEach items="${Data}" var="d">
        <option value="${d}">${d}</option>
    </c:forEach>      
</select>
</form>
</body>

我的Servlet页面DropDown.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
int[] day=new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};

    request.setAttribute("Data", day);

 response.sendRedirect("DropDown.jsp");
}

2 个答案:

答案 0 :(得分:1)

<强> 修改

的servlet

int[] day=new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};
request.setAttribute("Data", day);//<-- no loop required !
//response.sendRedirect("DropDown.jsp");//<-- this will make a new request
request.getRequestDispatcher("DropDown.jsp").forward(request, response);//<-- forward it

DropDown.jsp:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<select name="Day">
    <option>Day</option>
    <c:forEach var="d" items="${Data}">
      <option value="${d}">${d}</option>
    </c:forEach>
</select>

答案 1 :(得分:0)

for(int i=1;i<=day.length;i++)
    {
        request.setAttribute("data", day[i]);
    }       

它将覆盖data属性并替换新值。只需使用数组设置属性。

了request.setAttribute(&#34;数据&#34;,日);

然后在select中使用JSTL并导入jstl标记库

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<select name="Day">
   <c:foreach items="${data}" var="d">
    <option>${d}</option>
    </c:foreach>
</select>