7

我正在对一个非常旧的应用程序进行更改。这是使用 Spring MVC 4。

我需要在 JSP for Spring 控制器中的 form:form 标记中发布数据。UI 是固定的,我只能在服务器端进行更改。根据我提交的表单中的特定字段,我希望在我的控制器处理程序方法参数中有正确的子对象实例。

例如,

class Payment {...}
class CardPayment extends Payment{...}
class CheckPayment extends Payment{...}

在 UI 表单中,会有一个名为 paymentType 的输入值。付款将是 commandObject 或 ModelAttribute

我希望我的 @PostMapping 控制器在参数中有正确的子对象。我不想在控制器代码中手动实例化它。

@PostMapping
public ModelAndView doSomePay(@ModelAttribute("payment") Payment paymentInput, BindingResult result){

现在我希望paymentInput上面的这个对象是 CardPayment 或 checkPayment 类型。

我试图创建一个@initBinder and WebDatabinder但实际上我有近 10 个子类,我需要为所有这些创建“编辑器”吗?

如果是,那么创建 propertyEditor 的最佳方法是什么?

@InitBinder
    public void initBinder(WebDataBinder binder, HttpServletRequest request) {
        String paymentType = request.getParameter("paymentType");

        PropertyEditor productEditor;
       //somehow I can find the correct child class that I need to see, for example CardPatment.class ,  Now how to do following 

       binder.set(Product.class,productEditor); ???
}
4

0 回答 0