0

I want to send multiple values from a table from a database from hashmap in java tp a jsp file.this is what i have done so far

    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 >>

<%
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"));
}

But this only gives the last Row of the table not all the results !! What needs to be changed ? thanks

Shivam Shaz
  • 13
  • 1
  • 5

2 Answers2

1

Consider this code:

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"));
}

Each time through the loop, which is for each row in the database or each result set row, you put the same entries in the Map with new values.

Each row overwrites the previous one.

You can't get them out in the JSP since you overwrote all but the last one.

There are several solutions. I would create a POJO class with the 4 properties and put each row result in a list. But, lets use your map idea:

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);

Now you have to change up the JSP a bit (ugly java code that it has in it):

<%
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"));
}
%>
Lee Meador
  • 12,829
  • 2
  • 36
  • 42
0

What needs to be changed ?

Code! data structure should be a Map of beneficiaryId - > BeneficiaryModel ( a class representing Beneficiary model

Map is the structure of unique keys to values

Also don't use java code in jsp

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438