Spring 3 @NumberFormat无法与form:input标签一起使用
问题内容:
我有一个Spring 3 MVC应用程序<mvc:annotation-driven />
。无法使 java.lang.Double
属性显示为<form:input>
标记中的货币。金额显示正确,但未应用格式。有指导吗?
spring配置:
<mvc:annotation-driven conversion-service="conversionService">
<mvc:argument-resolvers>
<bean class="com.my.SessionUserHandlerMethodArgumentResolver"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.my.StringToDoubleConverter" />
</list>
</property>
</bean>
域实体字段注释:
import org.springframework.format.annotation.NumberFormat;
import org.springframework.format.annotation.NumberFormat.Style;
@Entity
@Table(name="form_data_wire_transfers")
@PrimaryKeyJoinColumn(name="form_id")
public class WireRequestForm extends RequestForm {
private Double amount;
@Column(name="amount")
@NumberFormat(style=Style.CURRENCY)
public Double getAmount() {
return amount;
}
public void setAmount(Double amount) {
this.amount = amount;
}
}
控制器方式:
@RequestMapping(value="/forms/{formId}", method=RequestMethod.GET)
public String show(Model uiModel, @PathVariable("formId") Integer formId){
RequestForm form = formService.findOne(formId);
uiModel.addAttribute("form", form);
return "show/form";
}
视图:
<form:form modelAttribute="form" action="${saveFormUrl}" method="POST">
<!-- AMOUNT -->
<div>
<form:label path="amount">Amount</form:label>
<form:input path="amount" />
</div>
</form:form>
同样,我看到了价值,但它显示像这样 1111.0 对 $ 1,111.00 。
问题答案:
ConversionServiceFactoryBean
不注册默认格式器。
您需要使用FormattingConversionServiceFactoryBean
这样做如下
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.my.StringToDoubleConverter" />
</list>
</property>
</bean>
如果您只想使用NumberFormatAnnotationFormatterFactory
数字格式设置(处理@NumberFormat
注释)并禁用其其他默认格式设置,则请执行以下操作
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="registerDefaultFormatters" value="false" />
<property name="formatters">
<set>
<bean class="org.springframework.format.number.NumberFormatAnnotationFormatterFactory" />
</set>
</property>
<property name="converters">
<list>
<bean class="com.my.StringToDoubleConverter" />
</list>
</property>
</bean>
资料来源: Spring Docs