How to pass an object to the view Spring MVC3
10,210
Solution 1
The Model documentation lists 2 methods for adding attributes to a Model. You are using the version without supplying a name, so Spring will use a generated name. I think this generated name is not what you think it is.
You could add the model using model.addAttribute("users", users);
Solution 2
Thank you all, i solved it this way:
@RequestMapping(value="/showUsers")
@ModelAttribute("users")
public ArrayList<User> showUsers(){
return userList;
}
![JBoy](https://i.stack.imgur.com/0QpY8.png?s=256&g=1)
Comments
-
JBoy about 2 years
I have a simple test project in Spring 3, basically a method within the controller that fetches data from an arraylist and "should" pass them to a view Thsi is how the method looks like:
@RequestMapping(value="/showUsers") public String showUsers(Model model){ ArrayList<User> users=this.copy(); model.addAttribute(users); return "showUsers"; }
And here's the jsp (showUsers.jsp)
They both execute with no logs or warnings the view is displayed but without the
ArrayList<User>
data's :(<table align="center" border="1"> <tr> <td>Nr:</td><td>Name:</td><td>Email</td><td>Modify?</td> </tr> <c:forEach var="user" items="${users}" varStatus="status"> <tr> <td><c:out value="${status.count}"/></td><td><c:out value="${user.name}"/></td> <td><c:out value="${user.email}"/></td><td>Modify</td> </tr> </c:forEach> </table>
Any advice? Thank you!
-
JBoy about 13 yearsYou mean that by calling @ModelAttribute Spring actually uses Model addAttribute(Object attributeValue) in stead of Model addAttribute(String attributeName, Object attributeValue)?
-
andyb about 13 yearsYes, you could just use
@ModelAttribute
(the value is optional - see documentation) but again, Spring would be creating it's own name model attribute name. However you are supplying the value "users", which is what is making it work.