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

标签 java spring jsp spring-mvc spring-form

我有

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/

相关文章:

java - 如何通过分隔逗号(,)来存储数据库中的选择框值?

jsp - 如何在JSP表达式语言中将int转换为char?

java - 如何让 Accordion 正确显示动态信息

java - Play-Framework - 禁用公用文件夹修改重新加载

java - 如何将基本引用类型变量转换为原始变量?

javascript - 每次重新加载 JSP 时都会加载外部 Javascript

java - 检查 URL 输入流是否包含 GIF

spring Vault 位置 [secret/my-application] 不可解析 : Not found

java - Spring验证,如何让PropertyEditor生成特定的错误消息

spring - 如何在 Spring Boot 2 应用程序中配置多个子上下文?