spring 3.0 MVC seems to be ignoring messages.properties - model-view-controller

Spring 3.0 MVC
First of all, I haven't found any documentation regarding messages.properties # springsource Everything I've found about overriding error messages has been on various forums. If anyone has a reference to where messages.properties is documented that'd be fantastic. Maybe messages.properties comes not from spring but a java spec?
I have tried following the advice on
JSR-303 Type Checking Before Binding My goal is to replace some type mismatch error messages with my own user friendly error messages
My situation is as follows:
Model
public class Test {
private int numberbomb;
public int getNumberbomb() {
return numberbomb;
}
public void setNumberbomb(int numberbomb) {
this.numberbomb = numberbomb;
}
}
myservlet.xml
<mvc:annotation-driven/>
jsp
<form:form id="test" method="post" modelAttribute="test">
<form:errors path="*"/>
<form:label path="numberbomb">numberbomb</form:label>
<form:input path="numberbomb"/>
</form:form>
classes\messages.properties
typeMismatch=bad value you bad bad person
test.numberbomb=you are driving me crazy with these bad inputs
Output from the form
Failed to convert property value of type java.lang.String to required type int for property numberbomb; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "three" from type java.lang.String to type int; nested exception is java.lang.NumberFormatException: For input string: "three"
BindingResult.toString() within my controller
Field error in object 'test' on field 'numberbomb': rejected value [three]; codes [typeMismatch.test.numberbomb,typeMismatch.numberbomb,typeMismatch.int,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [test.numberbomb,numberbomb]; arguments []; default message [numberbomb]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'int' for property 'numberbomb'; nested exception is org.springframework.core.convert.ConversionFailedException: Unable to convert value "three" from type 'java.lang.String' to type 'int'; nested exception is java.lang.NumberFormatException: For input string: "three"]
Is displaying the error messages with <form:errors> the wrong way display custom error messages? Do I need to add something to spring config files to tell it to look at messages.properties? Spring seems to be ignoring my messages.properties file (which is located in the WEB-INF\classes folder)
Thanks for any ideas!

An associate of mine pointed me in the right direction. I changed the messageSource bean in myservlet.xml
from
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="messages" />
<property name="cacheSeconds" value="1" />
</bean>
to
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages"/>
</bean>
For whatever reason this solved the problem. Thanks associate! :)

Related

Casting a String property to int in Spring config file

I have a properties file test.properties
HOST = http://localhost
PORT = 1234
In my config file I am passing the values from the properties file to a bean constructor-arg.
<util:properties id="nodeProperty"
location="classpath:config/test.properties" />
<context:property-placeholder
properties-ref="nodeProperty" />
<bean id="client" class="com.abc.client.ReadWrite">
<constructor-arg value="${HOST}" index="0"/>
<constructor-arg value="${PORT}" index="1" type="int"/>
</bean>
When I run this I get the following error
Unsatisfied dependency expressed through constructor argument with index 1 of type
[int]: Could not convert constructor argument value of type [java.lang.String] to
required type [int]: Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "8002;"
Look at the end of error message - For input string: "8002;"
I think it is incorrect value for PORT property.

Using <form:select> and <form:option> with converter but conversion does not happens, why?

I have this form for creating an Enrichment:
<form:form method="post" action="..." modelAttribute="enrichment">
...
<form:select path="tag">
<form:options items="${tagList}" itemValue="id" itemLabel="label" />
</form:select>
...
The Enrichment class has a Tag attribute. So when th user has selected a tag in the Tag list, tag.id (wich is a String) is sent throught the form. I don't think I could directly send a tag object am I wright? So I wrote a Converter to convert a String to a Tag, according to http://static.springsource.org/spring/docs/current/spring-framework-reference/html/validation.html#core-convert-Converter-API. So I did this :
public class IdToTagConverter implements Converter<String, Tag> {
#Autowired
TagService tagService;
public Tag convert(String id) {
return tagService.findTagById(Integer.parseInt(id));
}
}
And I created the bean :
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="exemple.IdToTagConverter"/>
</list>
</property>
</bean>
And I thought it would do the convertion automatically. But the error message is still here :
[Failed to convert property value of type 'java.lang.String' to
required type 'exemple.Tag' for property 'tag'; nested exception is
java.lang.IllegalStateException: Cannot convert value of type
[java.lang.String] to required type [exemple.Tag] for property 'tag':
no matching editors or conversion strategy found]
What did I miss?
Found the solution here :
http://forum.springsource.org/showthread.php?84003-Converters-no-matching-editors-or-conversion-strategy-found
I just replaced
<mvc:annotation-driven />
by
<mvc:annotation-driven conversion-service="conversionService" />
and it worked. Why? Spring MVC Voodoo.
Looks like Spring is not aware of your converter, or Conversion Service. Follow this part of the documentation to register your custom converter - > http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/validation.html#format-configuring-FormattingConversionService

Spring validations default messages

I need to get the resolved error messages programmatically in the controller. The default validation message for typeMismatch errors are not populating from my messages.properties file. I have a form backing object where a field is an Integer. If I submit a string for that field I get:
Failed to convert property value of type 'java.lang.String' to required type 'java.lang.Integer' for property 'establishedYear'; nested exception is java.lang.NumberFormatException: For input string: "1995a"
as the default message in the ObjectError. Here's my controller that output it:
#RequestMapping(method = RequestMethod.POST)
public #ResponseBody FormJSONResponse postForm(#Valid ProfileEditCompanyForm profileEditCompanyForm, BindingResult result) throws Exception {
if (result.hasErrors()) {
for (ObjectError objectError : result.getAllErrors()) {
System.out.println(objectError.getDefaultMessage()); // THIS IS NOT MY MESSAGE, BUT SHOULD BE
}
}
... other stuff ...
}
So I added a messages.properties to WEB-INF/classes with some test messages to see if I could override that default message:
typeMismatch.profileEditCompanyForm.establishedYear=test 1
typeMismatch.establishedYear=test 2
typeMismatch.java.lang.Integer=test 3
typeMismatch=test 4
profileEditCompanyForm.establishedYear=test 5
establishedYear=test 6
In my app-servlet.xml file I have:
<mvc:annotation-driven conversion-service="conversionService" validator="validator"/>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages" />
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource"/>
</bean>
Why isn't it picking up any of my messages from my messages.properties file?
Try this in you Spring context instead:
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="WEB-INF/classes/messages" />
</bean>
Then inside "WEB-INF/classes" folder create a file call: "messages.properties"
Take note for the content of "messages.properties" you have to provide it like this :
typeMismatch.pathValueInsideYourJSPform:input= Your Message
Hope this helps you !
here is a sample also
Try specifying the complete path and try
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="WEB-INF/messages" />
</bean>
Apparently I have to run the FieldError objects through the Spring MessageSource. I was hoping this was done automatically. I found my answer here:
How to get error text in controller from BindingResult

char[] to String Conversion in Spring configuration

I have bean A that returns an attribute as char[] and another bean that expects an attribute as String and I would like to inject the attribute from bean A to bean B.
When I do this:
<bean id="B" class="....">
<property name="password" value="#{A.password}" />
</bean>
<bean id="A" class="...">
</bean>
The error I'm getting is:
Cannot convert value of type [char[]] to required type [java.lang.String] for property 'password': no matching editors or conversion strategy found
Any idea how to resolve this?
Perhaps by using an expression language syntax?
Perhaps by registering some sort of a converter like org.springframework.beans.propertyeditors.CharArrayPropertyEditor in the configuration before injecting the char[] attribute?
Looks like this will work:
<property name="password" value="#{new java.lang.String(A.password)}" />

BeanInstantiationException:Cannot convert type from java.lang.String to required type --- idref tag

I am new to spring and trying to understand the functionality of the idref tag
My config file is pasted here:
<bean id="AudioSystembean" class="com.springexample.AudioSystem">
<property name="price" value="200"/>
</bean>
<bean id="Vehicle1" class="com.SpringExample.Vehicle1">
<property name="vehicleType" value="CAR" />
<property name="audioSystem" >
<idref bean = "AudioSystembean" />
</property>
</bean>
When I am executing the code I am getting the error as : "BeanInstantiationException:Cannot convert type from java.lang.String to required type :com.SpringExampl.AudioSystem" [I dont remember the exact exception - I have the code at home]
If I use ref instead of idref it is working fine.
I tried google to understand about idref but could not get much information..
What am I doing wrong here?
In a Spring context, <idref> is used to pass the name of the referenced bean, rather than the bean itself (which is what <ref> does). So in your example:
<property name="audioSystem" >
<idref bean = "AudioSystembean" />
</property>
The audioSystem system property will be injected with the name of the AudioSystembean, i.e. the String "AudioSystembean".
This is not what you need here, though, you need the <ref> element, which passes a reference to the bean itself.

Resources