首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在同一页中使用JSTL或JSP标准操作创建和使用ArrayList

问如何在同一页中使用JSTL或JSP标准操作创建和使用ArrayList
EN

Stack Overflow用户
提问于 2016-01-08 13:15:12
回答 2查看 549关注 0票数 0

我有一个抄写代码,它连接到数据库,获取记录,存储在数组列表中,并迭代数组列表以获取记录。

下面是连接和获取数组记录的代码

代码语言:javascript
复制
<%
    String connectionURL = "jdbc:mysql://localhost:3306/stc";
    ArrayList<String> productname = new ArrayList<String>();
    ArrayList<String> productmodel = new ArrayList<String>();
    Connection connection = null;
    ResultSet rs = null;
    try
    {
        // Load the database driver
        Class.forName("com.mysql.jdbc.Driver");
        // Get a Connection to the database
        connection = DriverManager.getConnection(connectionURL, "root", "");
        //Add the data into the database
        PreparedStatement pst = connection.prepareStatement("SELECT * FROM tbl_products");
        rs= pst.executeQuery();
        while(rs.next())
        {
            productname.add(rs.getString("txtProduct_Name"));
            productmodel.add(rs.getString("txtModel_No"));

        }

    }
    catch(Exception e){
        e.printStackTrace();
    }
    finally{
        if(connection != null){
            try {
                connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    %>

下面的代码遍历数组列表以显示记录

代码语言:javascript
复制
<select name="productname" id="productname">
            <option>Select Name</option>
            <%
                        for(int i=0;i<productname.size();i++)
                        {
                        %>
                        <option value="<%=productname.get(i) %>"><%=productname.get(i) %></option>
                        <%
                        }
            %>
            </select>

我希望通过使用JSTL或JSP标准操作来实现所有这些功能。请帮帮忙

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-01-08 13:39:22

以上代码可以重新分解以使用JSTL。在这种情况下可能需要的JSTL是Core,SQL标记。

代码语言:javascript
复制
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

对于第一个代码段,可以使用sql:setDataSource、sql:query标记连接到DB并执行查询。

代码语言:javascript
复制
 <sql:setDataSource var="demoDB" driver="com.mysql.jdbc.Driver"
         url="jdbc:mysql://localhost/demo"
         user=""  
         password=""/>

<sql:query dataSource="${demoDB}" sql=" " var="queryResult" />
  • sql属性将包含查询。

使用对象c:forEach上的queryResult标记迭代列表。

请参阅线程:Java ArrayList using in JSTL()

票数 0
EN

Stack Overflow用户

发布于 2016-01-08 13:32:07

您可以使用foreach在jstl中迭代ArrayList productname,如下所示:

代码语言:javascript
复制
   <c:forEach var='parameter' items='${productname}'>  
      <c:out value="${parameter.name}" /> 
    ...
   </c:forEach><br>

你对另一个ArrayList productmodel也是这样。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34678011

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档