I’m trying to create a form using Spring @MVC 3.0. This form is supposed to let the user update the flavor of a soup, but I’m running into some issues. Here are my relevant model classes (assume all the getters and setters are there):
public class Soup {
String name, flavor, mainIngredient;
public String toString()
{
return "name: " + this.name + ", flavor: "
+ this.flavor + ", main: " + this.mainIngredient;
}
}
public class SmallMeal {
List<Soup> soups;
}
public class Menu {
String id;
SmallMeal smallMeals;
}
This part of the application allows the user to edit the soups. Here’s the controller:
public class MenuController {
@RequestMapping(value="/soupForm", method = RequestMethod.GET)
public String updateSoups(
@PathVariable("menuId") String menuId,
ModelMap model)
{
Menu menu = // ... looked up with a DAO.
if (menu != null)
{
model.addAttribute("menu", menu);
for (Soup s : menu.getSmallMeal().getSoups())
{
System.out.println("soup: " + s.toString());
}
}
return "soupEditor";
}
@RequestMapping(value="/soupForm", method = RequestMethod.POST)
public String updateSoups(
@ModelAttribute("menu") Menu menu,
BindingResult result, SessionStatus status)
{
for (Soup s : menu.getSmallMeal().getSoups())
{
System.out.println("soup: " + s.toString());
}
return "redirect:soupUpdated";
}
}
And here’s the soupForm JSP:
<form:form modelAttribute="menu">
<c:forEach var="soup" varStatus="stat" items="${menu.smallMeal.soups}">
<label>${soup.name} flavor</label>
<form:input path="smallMeal.soups[${stat.index}].flavor" />
</c:forEach>
</form:form>
Now, when I first request the page, I get an output similar to this:
name: tortilla, flavor: spicy, mainIngredient: tortillas
name: crab bisque, flavor: crab, mainIngredient: crab
And after I submit the form (after updating the flavor for tortilla), I would get an output similar to:
name: null, flavor: delicious, mainIngredient: null
name: null, flavor: null, mainIngredient: null
What’s going wrong? Why isn’t the rest of the data of the object being bound?
Turns out that the
@SessionAttributesannotation was the answer.After that was added, the data currently existing on the object persisted.