Spring 5 Binder @InitBinder无法正确填充模型

时间:2018-10-27 12:02:23

标签: spring-mvc

我正在将Spring 2.5 Web应用程序升级到Spring 5.0.3。我正在使用字符串形式的标签。在我的控制器中,我有:

@InitBinder
public void initBinder(WebDataBinder binder, HttpServletRequest request) {

    CapTypeEditor capTypeEditor = new CapTypeEditor(this.getDAOFactory());
    binder.registerCustomEditor(CapType.class, "order.capType.id", capTypeEditor);
}

我看到这在GET上两次被调用(为什么?),在POST上两次被调用。在GET上,request.getParameter(“ order.capType.id”)为null,在POST中具有正确的ID。但是然后在我的Submit()POST方法中,capType不为null,但仅填充了id,而没有其名称:

@RequestMapping(value = "/es/orderinfo.html", method=RequestMethod.POST)
public ModelAndView submit(@RequestParam("id") long id,
        @ModelAttribute("command")OrderInfoBean bean, 
          BindingResult errors, ModelMap model,
          HttpServletRequest request) { 


    Order order = bean.getOrder();
    CapType ct = order.getCapType();
...
}

我的CapType编辑器从未调用:

public class CapTypeEditor extends PropertyEditorSupport {

DAOFactory daoFactory;

public CapTypeEditor(DAOFactory daoFactory){
    this.daoFactory = daoFactory;       
}

public void setAsText(String text){
    if(StringUtils.isBlank(text)||StringUtils.isEmpty(text) ){
        this.setValue(null);
        return;
    }
    Long id = Long.valueOf(text);
    CapType capType = daoFactory.getCapTypeDAO().read(id);
    this.setValue(capType);
}

public String getAsText(Object value){
    if(value == null) return StringUtils.EMPTY;
    CapType capType  = (CapType)value;
    return capType.getId().toString();
}
}

我的JSP如下:

<form:select path="order.orderType.id" tabindex="100" cssStyle="width:149px">
    <form:option value="">none</form:option>
    <form:options items="${refData.orderTypes }" itemValue="id" itemLabel="typeName" />                                 
</form:select>

2 个答案:

答案 0 :(得分:0)

您在注册自定义编辑器时放置了无效的属性路径。这样做:

binder.registerCustomEditor(CapType.class, "capType", capTypeEditor);

假定OrderInfoBean包含字段capType

binder.registerCustomEditor(CapType.class, "order.capType", capTypeEditor);

包含OrderInfoBean的{​​{1}}个连动Order

在JSP中,直接将 CapType capType用作绑定路径。

答案 1 :(得分:0)

实际上,我在@InitBinder中注册的旧编辑器还可以。 @minarmahmud关于.id中没有.id是正确的。将适当的equals和hashcode函数添加到我的休眠映射模型类(例如CapType)后,所有东西都起作用了,视图HTML上的默认值以及POST上我的模型的全自动映射都实现了。因此在Model CapType中:

jsonFilterBy:[ searchText, 'name, other, other2...']