-1

My servlet generates and sends an array to jsp. How can I achieve the following result:

If item = "dress", print.out "blue dress, size: medium"

Servlet part:

ArrayList<LinkedHashMap<String, String>> listData = new ArrayList<LinkedHashMap<String, String>>();
LinkedHashMap<String, String> linkedHashMap = new LinkedHashMap<String, String>();

linkedHashMap.put("item", "dress");
linkedHashMap.put("desc", "blue dress");
linkedHashMap.put("size", "medium");
listData.add(linkedHashMap);

linkedHashMap = new LinkedHashMap<String, String>();
linkedHashMap.put("item", "t-shirt");
linkedHashMap.put("desc", "white dress");
linkedHashMap.put("size", "small");
listData.add(linkedHashMap);

request.setAttribute("dataList", listData);

JSP part:

if (request.getAttribute("dataList") != null) {
    ArrayList basicList = (ArrayList) request.getAttribute("dataList");

    for (int i=0; i < basicList.size(); i++) {
        System.out.println(basicList.get(i));
    }
}

Results

{item=dress, desc=blue dress, size=medium}
{item=t-shirt, desc=white dress, size=small}

How can I achieve the following result: if item = "dress", print "blue dress, size: medium"

Myroslav Tedoski
  • 301
  • 3
  • 14

2 Answers2

1

If you want to display something in JSP, use the proper technologies, these are EL and JSTL:

<c:forEach items="${dataList}" var="dress">
    <p>${dress['desc']}, size: ${dress['size']} </p>
</c:forEach>
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • Will I be able to mix plain JSP with elements of EL and JSTL in it? App was written way back and I just can't rewrite it all now... – Myroslav Tedoski Jan 14 '16 at 12:40
  • It will depend on Servlet and JSP version. If you could share your application server name and version and Java version as well, I would tell you if this approach will work. – Luiggi Mendoza Jan 14 '16 at 14:37
1

Do you have to use a LinkedHashMap? I think it would be much easier to use an ArrayList and a separate class Item with desc and size as attributes. This would be the class:

public class Item {
    public String desc;
    public String size;

    public Item (String desc, String size) {
        this.desc = desc;
        this.size = size;
    }
}

I guess you could also use an enum for size (since it will be only "small", "medium", "large" and so on).

Your Servlet part would look like this:

ArrayList<Item> listData = new ArrayList<Item>();
listData.add(new Item("blue dress", "medium"));
listData.add(new Item("white dress", "small"));
request.setAttribute("dataList", dataList);

And your JSP part like this:

if (request.getAttribute("dataList") != null) {
    ArrayList basicList = (ArrayList) request.getAttribute("dataList");

    Item myItem = null;
    for (int i=0; i < basicList.size(); i++) {
        myItem = (Item)basicList.get(i)
        System.out.println(myItem.desc + ", size: " + myItem.size);
    }
}

I didn't try the code, but I think this should be working.