Convert string with commas to double number in spring MVC - java

i am currently using MappingJacksonHttpMessageConverter in my Dispatcher-Servlet.xml. In my application when the user enters a currency, commas are itself attached to the value. When that value is passed to the controller it is unable to convert the string with commas to a double value. throws pare error. I am using this value for other calculations so i cannot change its type to string in the modal class.
Is there a way we can can use MappingJacksonHttpMessageConverter to make the controller ignore the commas and read the value.
This is part of my servlet.xml file.
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="order" value="1" />
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
Any help would be appreciated

You can do this by creating custom conversion service in spring by implementing Converter interface.
For info on this see http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/validation.html
and
http://log4aj.blogspot.in/2012/08/spring-converterconversionservice.html.

Related

Creating a restful method that takes a posted xml and creates an entity

How can I take an xml that looks like:
<request>
<User>
<name>name value</name>
<age>13</age>
</User>
</request>
And then I can deserialize this into a User object that has matching properties.
public class User {
private String name;
private Integer age;
// getter and setters
}
Is there anything simple I can do or do I have to parse the xml manually for this?
I'm using spring mvc, and this is in a method where the xml will be posted.
Your controller method should take an argument of type User, which is annotated with #RequestBody. Then you need to configure a MarshallingHttpMessageConverter with an appropriate marshaller/unmarshaller. An example, straight from the reference guide:
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<util:list id="beanList">
<ref bean="stringHttpMessageConverter"/>
<ref bean="marshallingHttpMessageConverter"/>
</util:list>
</property
</bean>
<bean id="stringHttpMessageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean id="marshallingHttpMessageConverter"
class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter">
<property name="marshaller" ref="castorMarshaller" />
<property name="unmarshaller" ref="castorMarshaller" />
</bean>
<bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller"/>
Take a look at "Supported method argument types" and "Mapping the request body with the #RequestBody annotation" in the reference guide for more details.
You can use Digest.
It will bind your XML elements to your POJOs.
Here is a complete tutorial :
http://onjava.com/pub/a/onjava/2002/10/23/digester.html

Common value configuration in Spring XML

I have several Spring beans in which one of the property value for all of them are same String value. Is there a way where I can define this String in XML at one place and refer it in all beans at property value settings?
<bean id="somebean" class="test.SomeBean">
<property name="property1" ref="someValue"></property>
<property name="commonProperty" value="commonValue"></property>
<bean id="nextBean" class="test.NextBean">
<property name="property2" ref="someValue"></property>
<property name="commonProperty" value="commonValue"></property>
How to set commonValue in a seperate place and refer it in both places?
Try like this.
<bean id="commonConfig" abstract="true">
<property name="commonField" value="CommonValue"></property>
</bean>
<bean id="class1" class="com.dataclass.Class1" parent="commonConfig">
<property name="field1" value="value1"></property>
</bean>
<bean id="class2" class="com.dataclass.Class2" parent="commonConfig">
<property name="field2" value="value2"></property>
</bean>
Class1 & Class2 having one common field name "commonField", parent attribute is use for this common purpose only.
In Spring this is called bean definition inheritance(this is not java class inheritance, above example Class1 & n Class not inheriting in their respective java file.)
For more detail, look at Spring doc's link.
I've never tried it before, but this should work
<bean id="commonProp" class="java.lang.String">
<constructor-arg name="original" value="yourString"></constructor-arg>
</bean>
Then, in every bean you need to reference it:
<bean id="somebean" class="test.SomeBean">
<property name="property1" ref="someValue"></property>
<property name="commonProperty" ref="commonProp"></property>
</bean>
You can define your string properties in some "init_constants.properties" file. Then you should load properties file in spring xml:
<bean id="properties"
class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:db.properties</value>
<value>classpath:mail.properties</value>
<value>classpath:init_constants.properties</value>
</list>
</property>
</bean>
And after that you can inject this properties using xml:
<bean id="somebean" class="test.SomeBean">
<property name="property1" ref="{$prop1}"></property>
<property name="commonProperty" value="commonValue"></property>
</bean>
or in code using #Value annotation:
#Value(value="${prop1}")
private String property1;
Well If commonValue is string then you can put it in properties file and read it using #Value annotation.

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

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 allows 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>

Declaring an array of objects in a Spring bean context

I'm trying to create an array of objects in a Spring context file so I can inject it to a constructor that's declared like this:
public RandomGeocodingService(GeocodingService... services) { }
I'm trying to use the <array> tag:
<bean id="googleGeocodingService" class="geocoding.GoogleGeocodingService">
<constructor-arg ref="proxy" />
<constructor-arg value="" />
</bean>
<bean id="geocodingService" class="geocoding.RandomGeocodingService">
<constructor-arg>
<array value-type="geocoding.GeocodingService">
<!-- How do I reference the google geocoding service here? -->
</array>
</constructor-arg>
</bean>
I haven't been able to find an example or something in the in the documentation on how to do this. Also, you have any suggestions for a better way of acheiving what I'm trying to do, please let me know :).
That's because there's no such thing as <array>, there's only <list>.
The good news is that Spring will auto-convert between lists and arrays as required, so defined your array as a <list>, and Spring will be coerce it into an array for you.
This should work:
<bean id="googleGeocodingService" class="geocoding.GoogleGeocodingService">
<constructor-arg ref="proxy" />
<constructor-arg value="" />
</bean>
<bean id="geocodingService" class="geocoding.RandomGeocodingService">
<constructor-arg>
<list>
<ref bean="googleGeocodingService"/>
</list>
</constructor-arg>
</bean>
Spring will also coerce a single bean into a list, if required:
<bean id="geocodingService" class="geocoding.RandomGeocodingService">
<constructor-arg>
<ref bean="googleGeocodingService"/>
</constructor-arg>
</bean>
Spring can automatically convert a list into an array[]
check it out http://forum.springsource.org/showthread.php?37767-Injecting-String-Array
<bean name="test" class="Test">
<property name="values" value="hugo,emil"></property>
</bean>
Check out the util schema.
I'm actually using <array> tag to inject an array of objects into a bean and it works.
Take a look at the following code...
<bean id="song1" class="mx.com.company.songs.Song">
<property name="name" value="Have you ever seen the rain?"/>
</bean>
<bean id="song2" class="mx.com.company.songs.Song">
<property name="name" value="La bamba"/>
</bean>
<bean id="guitarPlayer" class="mx.com.company.musician.GuitarPlayer">
<property name="songs">
<array>
<ref bean="song1"/>
<ref bean="song2"/>
</array>
</property>
</bean>

Declaring Integers, Doubles, Floats, Strings etc. in Spring XML

Occasionally, Spring can't figure out what type a "value" should be. This happens when the property or constructor is of type "java.lang.Object". In these cases, Spring defaults to "java.lang.String". Sometimes this isn't the right choice, for example when using:
<jee:jndi-lookup id="test" jndi-name="java:comp/env/test"
default-value="10" expected-type="java.lang.Integer"/>
If the lookup fails and it has to fall back to the default-value, there's a type mismatch. So, instead, this needs to be done:
<bean id="test" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/test" />
<property name="defaultObject">
<bean class="java.lang.Integer">
<constructor-arg value="10" />
</bean>
</property>
</bean>
which is somewhat verbose, especially if there are lots of them. Is there some handy way to declare an Integer / Long / Double / Float / String literal without having to use this format:
<bean class="java.lang.Integer">
<constructor-arg value="10" />
</bean>
Since Spring 3.0, you can use Spring Expression Language: #{new Integer(10)}
<jee:jndi-lookup id="test" jndi-name="java:comp/env/test"
default-value="#{new Integer(10)}" expected-type="java.lang.Integer"/>
You should be able to do:
<constructor-arg value="10" type="int"/>
See section 3.3.1.1.1.1 of the Spring Reference

Categories

Resources