开发者

What should i use i if need a custom converter when using @RequestParam?

开发者 https://www.devze.com 2023-01-20 15:22 出处:网络
I if have a method signature as follows public void deposit(@RequestParam(\"accountId\") Integer accountId,

I if have a method signature as follows

public void deposit(@RequestParam("accountId") Integer accountId, 
                    @RequestParam("amount") BigDecimal amount) {...}

And because i have a locale specific decimal value which needs to be converted to a BigDecimal, is there some annotation which a开发者_运维技巧llows me to set up incoming data such as @Decimal("###.###,##") or something else ???


Spring 3 has @NumberFormat annotation:

public void deposit(@RequestParam("accountId") Integer accountId,  
    @RequestParam("amount") @NumberFormat(pattern = "###.###,##") BigDecimal amount) 
{...} 

You need <mvc:annotation-driven> to enable it.

See also:

  • Spring MVC 3 Showcase


More generically you can register a custom converter with the ConversionServiceFactoryBean. Once you do that you will need to add a custom web binding initializer to your handler adapter

Example Config:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="webBindingInitializer">
      <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
          <property name="conversionService" ref="conversionService"/>
      </bean>
    </property>
</bean>

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
    <property name="converters">
        <list>
            <ref bean="myCustomConverter"/>
        </list>
    </property>
</bean>    
0

精彩评论

暂无评论...
验证码 换一张
取 消