2

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

弹簧配置:

<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

4

1 回答 1

1

ConversionServiceFactoryBean不注册默认格式化程序。

你需要使用FormattingConversionServiceFactoryBean
所以做如下

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <bean class="com.my.StringToDoubleConverter" />
        </list>
    </property>
</bean>



如果您只想使用NumberFormatAnnotationFormatterFactoryNumber Formatting (处理@NumberFormatAnnotation )并禁用其其他默认格式化程序,请执行以下操作

<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

于 2013-08-29T17:46:53.950 回答