1

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

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

当我提交表单数据时,我的控制器会抛出这个异常: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());
    }
}

而我的 JSP 上的表单,现在我只想提交类型并看到它转换为该类型的空食物对象。

<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>
4

1 回答 1

0

我可以通过更改表单的输入来修复它

<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>
于 2018-10-30T19:22:12.047 回答