如何使用SpringMVC将多个对象或模型放在一个表单中
我必须为两个modelAttribute使用一个表单:“groupes”是一个Groupe列表,“matieres”是一个Matiere列表,我知道一个表单只支持一个modelAttribute,我尝试了两个选项,但都不起作用,一个是使用spring bind标记,另一个是将groupes和Matiere包装在一个类中, 有什么办法解决这个问题吗如何使用SpringMVC将多个对象或模型放在一个表单中,spring,spring-mvc,Spring,Spring Mvc,我必须为两个modelAttribute使用一个表单:“groupes”是一个Groupe列表,“matieres”是一个Matiere列表,我知道一个表单只支持一个modelAttribute,我尝试了两个选项,但都不起作用,一个是使用spring bind标记,另一个是将groupes和Matiere包装在一个类中, 有什么办法解决这个问题吗 @RequestMapping(method = RequestMethod.GET) public ModelAndView showForm()
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showForm() {
ModelAndView mv = new ModelAndView("abs");
mv.addObject("matiere", matiereservice.findAlmatieres());
mv.addObject("groupe", groupeservice.findAllGroupes());
return mv;
}
@RequestMapping( method = RequestMethod.POST)
public String submitForm( @ModelAttribute("groupe") Groupe groupe, @ModelAttribute("matiere") Matiere matiere,
ModelMap map,
BindingResult result
) {
// BindingResult treatment
return "listeleve" ;
}
不要单独发送这些属性,只需创建一个DTO类,其中包含
Groupe
和Matiere
类的List
字段
public class ListeleveDTO {
private List<Groupe> groupe;
private List<Matiere> matiere;
public ListeleveDTO(List<Groupe> groupe, List<Matiere> matiere) {
// Assign to fields
}
// getters and setters
}
感谢您的回复,我尝试了一下,但在提交表单时出现了一个错误:HTTP状态400-客户端发送的请求在语法上不正确,您知道这个问题吗?
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showForm() {
ModelAndView mv = new ModelAndView("abs");
mv.addObject("listeleveDTO", new ListeleveDTO(groupeservice.findAllGroupes(), matiereservice.findAlmatieres());
return mv;
}
@RequestMapping( method = RequestMethod.POST)
public String submitForm( @ModelAttribute("listeleveDTO") ListeleveDTO,
ModelMap map,
BindingResult result
) {
// BindingResult treatment
return "listeleve" ;
}