For a simple webapp, I'm trying to print value of ArrayList on jsp side is highly unintuitive. I'm having a hard time piecing this thing together.
This is a Spring Boot application and the following is what I send for a response --
@GetMapping("/")
public String welcome(Map<String, Object> model) {
List<APojo> lis = new ArrayList<>();
APojo po = new APojo();
po.setName("Apple");
po.setName("Ball");
lis.add(po);
model.put("fruits", lis);
return "index";
}
The index.jsp page --
<html>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>
<title>Title goes here</title>
</head>
<body>
<c:set var = "fruitVal" value = "${fruits[0].name}"/>
<h2>Value: ${fruitVal}</h2>
</body>
</html>
I expect it to display Apple, but it keeps printing Ball. Why?
You should add 2 objects to list (or remove po.setName("Ball");
) :
APojo po = new APojo();
po.setName("Apple");
lis.add(po);
po = new APojo();
po.setName("Ball");
lis.add(po);
Consider also using a constructor that accept name