我有
Class Shape {
//Implementation
}
Class Round extends Shape{
//Implementation
}
Controller 我有
@Requestmapping(value="/view/form")
public ModelAndView getForm(){
ModelAndView mav=new ModelAndView();
mav.addObject("shape",new Round());
}
@RequestMapping(value="/submit", method = RequestMethod.POST)
public ModelAndView submitForm(@ModelAttribute("shape") Shape shape){
if(shape instanceof Round){ //**Not giving positive result**
}
}
在 Jsp 中
<form:form action="/submit" commandName="shape" method="post">
//form tags
</form:form>
当我提交带有 Round 对象的表单时。在 Controller 端 ModelAttribute 没有给出 Round 的实例。它仅给出形状实例。如何做到这一点
最佳答案
这永远行不通
<form:form action="/submit" commandName="shape" method="post">
您正在从表单提交一个 shape
并期待一个 shape
在 Controller 方法中
public ModelAndView submitForm(@ModelAttribute("shape") Shape shape)
它永远不会给你一个 Round
对象。
只需从表单中提交一个 Round 对象并使用它。
<form:form action="/submit" commandName="round" method="post">
public ModelAndView submitForm(@ModelAttribute("round") Round round)
编辑:-
在表单中有一个 hiddenInput
类型,它将告诉 controller
它正在传递的 Shape
类型,您可以更改 hidden 的值动态标记
根据用户要求。
<input type="hidden" name="type" value="round">
获取 contoller
中类型的值并使用它来cast
Shape
对象
public ModelAndView submitForm(
@ModelAttribute("shape") Shape shape,
@RequestParam("type") String type)
{
if(type.equals("round")){
//if type is a round you can cast the shape to a round
Round round = (Round)shape;
}
}
关于java - 如何在 spring 表单中绑定(bind)子类对象作为 modelAttribute 提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37590406/