Spring 3 @NumberFormat不使用form:input Tag

时间:2013-08-29 15:25:42

标签: java spring spring-mvc jsp-tags

我有一个使用<mvc:annotation-driven />的Spring 3 MVC应用程序。无法将 java.lang.Double 属性显示为<form:input>标记中的货币。金额显示正确,但未应用格式。有什么指导吗?

Spring config:

<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

1 个答案:

答案 0 :(得分:1)

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