简体   繁体   English

将属性编辑器应用于模型中的对象

[英]Apply property editor to object in the model

I have a form and I have registered the CustomNumberEditor for the float numbers of my objects. 我有一个表单,并且已经为我的对象的浮点数注册了CustomNumberEditor。

@InitBinder
public void initBinder(WebDataBinder binder){
    NumberFormat numberFormat = NumberFormat.getInstance();
    binder.registerCustomEditor(Float.class, new CustomNumberEditor(Float.class, numberFormat, true));
}

I have an ajax controller method to update a section of the form (it just returns an updated html fragment) so in the controller I do something like this: 我有一个ajax控制器方法来更新表单的一部分(它只返回更新的html片段),因此在控制器中,我会执行以下操作:

public String retrieveFormSection(@PathVariable("id") String id, Model model) {
    ... 
    model.addAttribute("myObject", myObject);
    return "myJSP";
}

In that JSP I just want to print some data using the editors: 在该JSP中,我只想使用编辑器打印一些数据:

<input type="text" value="${myObject.myNumber}"/>

As myObject is not placed as a @ModelAttribute object the editor is not used for it. 由于myObject没有作为@ModelAttribute对象放置,因此不使用编辑器。 Is there any way to register the editors to the fields in the objects that I add to the model? 有什么方法可以将编辑器注册到我添加到模型中的对象的字段中? Maybe editors should not be used for this because in this way I'm only using the getAsText() method of the editor and not in the setAsText(). 也许不应为此使用编辑器,因为以这种方式,我仅使用编辑器的getAsText()方法,而不使用setAsText()。 Should I use another Spring feature for this? 我应该为此使用另一个Spring功能吗?

Thanks. 谢谢。

You can use <spring:bind> to display value processed by PropertyEditor : 您可以使用<spring:bind>来显示由PropertyEditor处理的值:

<spring:bind path = "myObject.myNumber">
    <input type="text" value="${status.displayValue}"/> 
</spring:bind>

However, if you need to render it in the input field, you can also use <form:input> , as with regular forms. 但是,如果需要在输入字段中呈现它,则也可以像常规表单一样使用<form:input> If you don't want it to be in a <form> , you can use <spring:nestedPath> instead of <form:form> : 如果您不希望它出现在<form> ,则可以使用<spring:nestedPath>而不是<form:form>

<form:form modelAttribute = "myObject">
    <form:input path = "myNumber" />
</form:form>

<spring:nestedPath path = "myObject">
    <form:input path = "myNumber" />
</spring:nestedPath>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM