【问题标题】:how to get values from class to jsp using arraylist?如何使用arraylist从类获取值到jsp?
【发布时间】:2014-01-15 09:15:54
【问题描述】:

嗨,我在使用 arraylist 从数据库中检索数据时遇到了一些问题。我只能获取该列的最后一个条目。这是我的代码,任何帮助表示赞赏。提前谢谢你。

这是我从数据库中获取数据的地方

VariableIntialization location = new VariableIntialization();
            HttpSession session = request.getSession();
          String sql = "SELECT * FROM country";
        Database db= new Database();
                          PreparedStatement pst = db.getConnection().prepareStatement(sql);
                         ResultSet i = pst.executeQuery();

                            while (i.next()) {
                                String country_id = i.getString(1);
                                String country = i.getString(2);
                            ArrayList<String> countries = new ArrayList<String>();
                                countries.add(country);
                                location.setcountry(countries);
                                location.setcountry_id(country_id);
                            }
    session.setAttribute("deshopa_country", location);
                response.sendRedirect("admin/stateadd.jsp");

这是我的 .java 类,其中数据进入..

package requirementlogic;

import java.util.ArrayList;

public class VariableIntialization {
    private ArrayList<String> content =new ArrayList<String>();
        public void setcountry(ArrayList<String> content)
                    {
                        this.content = content;

                    }
                 public ArrayList<String> getcountry() { return content; }
}

这是我要显示数据的 jsp 页面

<%@ page contentType="text/html; charset=utf-8" language="java" import="java.sql.*" errorPage="" %>
 <%@ page import = "requirementlogic.*"  %>
 <%@ page import = "java.util.ArrayList" %>
      <%VariableIntialization ds_country =(VariableIntialization)session.getAttribute("deshopa_country"); %>

    <% ArrayList<String> desham =new ArrayList<String>();
            desham = ds_country.getcountry();

<html>
<body>
<form method="get" action="../State" name="location" id="location">
<%if(session.getAttribute("deshopa_country") != null){ %>
<div class="span2"><select name="country_ref" id="country_ref" class="clear">
<%for(int i=0; i<desham.size() ;i++){ %>
<option><%=desham.get(i)%></option>

<%} %>
</select></div>
<%} %>
</form>
</body>
</html>

【问题讨论】:

  • 您的问题是什么?您在下拉菜单中只看到 1 个选项?
  • @Loc "是的,只有最后一个插入数据的选项"
  • 检查您的 servlet 代码。你的 while 循环是错误的,这就是为什么你的位置总是有 1 个国家。需要将 ArrayList 国家/地区移到 while/loop 之外。
  • @Loc "非常感谢我尝试了很多,现在它工作正常"

标签: java jsp arraylist


【解决方案1】:

每次您创建一个新的国家/地区列表时,因为它已添加到循环中,请在循环之外声明它,以便将结果集添加到列表中。因为您将其添加到列表中,所以您总是会得到一个新的仅包含一个国家/地区条目的列表

【讨论】:

    猜你喜欢
    • 2014-06-14
    • 2012-05-20
    • 2013-11-08
    • 2019-11-24
    • 2020-05-31
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多