如何从java中的HashMap向jsp发送表的多个值?

时间:2013-07-08 17:57:02

标签: java jsp hashmap

我想从java tp和jsp文件中的hashmap从数据库的表中发送多个值。这是我到目前为止所做的事情

    ResultSet rs = st.executeQuery("SELECT * FROM seeding where scheme = '"+user+"' "); 
    HashMap<String, String> verify = new HashMap<String, String>();
    while (rs.next())
    {
    verify.put("beneficiaryID",rs.getString("beneficiaryID"));
    verify.put("scheme", rs.getString("scheme"));
    verify.put("aadhaar",rs.getString("aadhaar"));
    verify.put("name",rs.getString("name"));
    }
    request.setAttribute("verify", verify);

jsp&gt;&gt;

<%
HashMap<String, String> verify = (HashMap<String, String>) 
request.getAttribute("verify");
for (String key : verify.keySet())  
{ 
out.print(verify.get("aadhaar"));
out.print(verify.get("scheme"));
out.print(verify.get("beneficiaryID")+"$"+verify.get("name"));
}

但是这只给出了表格的最后一行而不是所有的结果!! 需要改变什么? 谢谢

2 个答案:

答案 0 :(得分:1)

考虑以下代码:

HashMap<String, String> verify = new HashMap<String, String>();
while (rs.next())
{
    verify.put("beneficiaryID",rs.getString("beneficiaryID"));
    verify.put("scheme", rs.getString("scheme"));
    verify.put("aadhaar",rs.getString("aadhaar"));
    verify.put("name",rs.getString("name"));
}

每次循环(对于数据库中的每一行或每个结果集行),都会在Map中使用新值添加相同的条目。

每一行都会覆盖前一行。

你不能在JSP中删除它们,因为你覆盖了除最后一个之外的所有内容。

有几种解决方案。我将创建一个包含4个属性的POJO类,并将每行结果放在一个列表中。但是,让我们使用你的地图理念:

List results = new ArrayList<Map<String, String>>();
while (rs.next())
{
    Map<String, String> verify = new HashMap<String, String>();
    verify.put("beneficiaryID",rs.getString("beneficiaryID"));
    verify.put("scheme", rs.getString("scheme"));
    verify.put("aadhaar",rs.getString("aadhaar"));
    verify.put("name",rs.getString("name"));
    results.add(verify);
}
 request.setAttribute("verify", results);

现在你必须稍微更改一下JSP(它里面有丑陋的java代码):

<%
List<Map<String, String>> results = (List<Map<String, String>>)request.getAttribute("verify");
for (Map<String, String> verify: results) {
{ 
    out.print(verify.get("aadhaar"));
    out.print(verify.get("scheme"));
    out.print(verify.get("beneficiaryID")+"$"+verify.get("name"));
}
%>

答案 1 :(得分:0)

  

需要改变什么?

代码!数据结构应该是beneficiaryId - &gt;的映射。 BeneficiaryModel(代表Beneficiary模型的类

Map是值唯一键的结构

另外don't use java code in jsp