代码之家  ›  专栏  ›  技术社区  ›  Seephor

@springmvc中带有抽象类的ModelAttribute

  •  1
  • Seephor  · 技术社区  · 6 年前

    我试图将表单数据从JSP提交到控制器,并将数据绑定到基于表单中“type”字段的抽象类的两个实现之一。我看到这篇文章听起来很有希望,但是在创建并注册了一个转换器之后,它并没有被称为: @ModelAttribute and abstract class

    我错过了什么?接线看起来是正确的,但这也是我第一次尝试配置这个。

    当我提交表单数据时,我的控制器抛出以下异常: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.project.types.Food]: Is it an abstract class?

    下面是抽象类结构:

    abstract Food
    String type
    
    Banana extends Food
    Apple extends Food
    

    这是我的控制器:

    @RequestMapping(value = "/web/pickFood", method = RequestMethod.POST)
        public ModelAndView foodSubmit(@ModelAttribute("food") Food food) {...}
    

    我的转换器:

    public class FoodConverter implements Converter<String, Food> {
    
        @Override
        public Food convert(String type) {
            Food food = null;
            switch (type) {
                case "banana":
                    food = new Banana();
                    break;
                case "apple":
                    food = new Apple();
                    break;
                default:
                    throw new IllegalArgumentException("Unknown food type:" + type);
            }
            return food;
        }
    }
    

    如何注册转换器:

    @Configuration
    @EnableWebMvc
    public class FoodWebMvCContext extends WebMvcConfigurerAdapter {
        @Override
        public void addFormatters(FormatterRegistry registry) {
            registry.addConverter(new FoodConverter());
        }
    }
    

    <form:form method="POST"
                       action="/web/pickFood"
                       modelAttribute="food">
                <table>
                    <tr>
                        <td><form:label path="type">Type</form:label></td>
                        <td><form:input path="type" name="food"/></td>
                    </tr>
                </table>
     </form:form>
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Seephor    6 年前

    我可以通过将表单的输入从

    <tr>
        <td><form:label path="type">Type</form:label></td>
        <td><form:input path="type" name="food"/></td>
    </tr>
    

    <tr>
        <input type="text" name="food" />
    </tr>