2013-08-29 85 views
2

我有一個使用<mvc:annotation-driven />的Spring 3 MVC應用程序。無法將java.lang.Double屬性顯示爲<form:input>標記中的貨幣。金額正確顯示,但未應用格式。任何指導?Spring 3 @NumberFormat不能使用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> 

域實體領域annotaion:

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

+0

看看這個:http://stackoverflow.com/questions/14089688/numberformat-annotation-not-working –

+1

這應該沒有'工作'雖然對不對?不應該''也照顧綁定和格式? –

回答

1

ConversionServiceFactoryBean未註冊默認格式化程序。

您需要使用FormattingConversionServiceFactoryBean
如果你希望只使用NumberFormatAnnotationFormatterFactory這確實數字格式所以做如下

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



(處理@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

+0

非常好。太感謝了! –