gpt4 book ai didi

java - 如何在 spring 表单中绑定(bind)子类对象作为 modelAttribute 提交

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:24:32 24 4
gpt4 key购买 nike

我有

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com