【发布时间】: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 "非常感谢我尝试了很多,现在它工作正常"