Spring 5 <form> tags (input, select, etc…) n

2019-08-08 18:19发布

问题:

I am upgrading a web app from SPring 2.5 to Spring 5. My Controller shows a populated Model Object here;

@RequestMapping(value = "/es/orderinfo.html", method = RequestMethod.GET)
public ModelAndView initForm(
        @RequestParam("id") long id,
        HttpServletRequest request){


    Order order = getDAOFactory().getOrderDAO().load(id);

    OrderInfoBean bean = new OrderInfoBean();
    bean.setOrder(order);


    ModelAndView mv = new ModelAndView("es/orderinfo", "command", bean);
    return mv;

}

And in my JSP, if I put a typo in the path of a select, I get the runtime error indicating that the Spring runtime has correctly validated my command object. The correct path looks like:

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

...BUT after 15 hrs, the values of the model are not being used in any input fields, textareas, inputs, selects... ...so somehow there is a gap between the GET mapped controller function that is giving a populated formBackingObject (Model) and the JSP which sees that Class/Type but is not getting the data. BTW the reference data (e.g. refData.order.Types) is coming through to the JSPs fine....

回答1:

holi.scheiserama this works:

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

(danger soap box moment...) so it seems to me that the spring form tag with user defined types, works diferently now (5.0.3 vs 2.5) would have been nice to know 16 hrs ago... hope that helps, use path to id....



回答2:

That idea of adding .id to path actually breaks the subsequent post in terms of fully loading and joining types of a complex model (see the new formatters (after spring 3) and the old editors and so on). The correct fix is to add equals and hashcode functions to the CapType class like this:

 @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        final CapType capType = (CapType) o;
        return Objects.equals(id, capType.id) &&
        Objects.equals(typeName, capType.getTypeName());
    }
   @Override
   public int hashCode() {
       return Objects.hash(id, typeName);
   }

Thanks for the tip from here http://springinpractice.com/2012/01/07/making-formselect-work-nicely-using-spring-3-formatters



标签: spring-mvc