Spring mvc: controller returns [][], usable in jsp with foreach, but how to bind?
I'm building a spring mvc 开发者_如何学运维application. Now the problem I have is the following.
I have a controller which adds a DayInfo[][]
to my ModelMap
.
(DayInfo
has an id
, a title
(String
) and Text
(also String
).
Now the problem I have is that I have no problem displaying this DayInfo[][]
with <foreach>
tags in my jsp.
However I'm outputting the Title
property as an input box(type text), and I'd like to be able to update this value (and thus saving it to be a database but that shouldn't be a problem). However I'm having trouble with binding this value to the input box so that it is actually returned to the controller.
If anyone has some advice it would be welcome.
I have never done this with multidimensional arrays but it should be something like this (though I haven't tried it, it's just to give you an idea). In the JSP you should set the name of the input with each index, something like this:
<c:forEach var="row" items="${days}" varStatus="statusRow">
<c:forEach var="day" items="${row}" varStatus="statusCol">
<input type="text" name="days[${statusRow.index}][${statusCol.index}].title" value="${day.title}"/>
</c:forEach>
</c:forEach>
and in the controller you have to prepare days variable so the size of the array is the same as the one you get from the JSP. So you can use @ModelAttribute method to prepare the array (this method will be executed before the @RequestMapping method).
@ModelAttribute("days")
public getDays(){
DayInfo[][] days;
//Here you have to instantiate the days to prepare it so it can be filled
//You can load for example the data from the database
return days;
}
@RequestMapping("/yourURL")
public String getFormData(@ModelAttribute("days")DayInfo[][] days){
//Here in days you should have the data from the form overriding
// the one from the database
}
Hope this helps and sorry if there is any error, though I'm writing withoug trying it.
精彩评论