Does Spring MVC form submit data bind children objects automagically?
I have a data model that is something like this:
public class Report {
// report owner
private User user;
... typical getter setter ...
}
public class User {
... omitted for clarity
}
What happens is when a report is created, the current user is set to the report user object. When the report is edited, the spring controller handling the POST request is receiving a report where the user object is null. Here is what my controller looks like:
@Controller
@RequestMapping("/report")
public class ReportController {
@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
public String editReport(@PathVariable Long id, Model model) {
Report r = backend.getReport(id); // fully loads object
model.addAttribute("report", report);
return "report/edit";
}
@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
public String process(@ModelAttribute("report") Report r) {
backend.save(r);
return "redirect:/report/show" + r.getId();
}
}
I ran things throw the debugger and it looks like in the editReport method the model object is storing the fully loaded report object (I can see the user inside the report). On the form jsp I can do the following:
${report.user.usern开发者_如何学Goame}
and the correct result is rendered. However, when I look at the debugger in the process method, the passed in Report r has a null user. I don't need to do any special data binding to ensure that information is retained do I?
It seems that unless the object being edited is stored in the @SessionAttributes, then spring will instantiate a new object from the information included in the form. Tagging the controller with @SessionAttributes("report") resolved my issue. Not sure of the potential impact of doing so however.
精彩评论