1

I am using Spring MVC 3 and I try to use the validation annotation for the model object.

However I found that this validation will only work if there are no exceptions thrown.

Take this pojo for example:

public class Person{
    private String name;
    @Min(30)
    private int age;
}

Now,I will create new Person instance through the html form, the validation work if the type of the age is int.

But if not (for example, user input a string for the age), it will throw an exception.

And I want to know where to catch this exception and put its message in the error form field?


UPDATE:

servlet-context.xml

<mvc:annotation-driven />
<mvc:view-controller path="/" view-name="home" />
<context:component-scan base-package="com.king.controller" />
<mvc:resources mapping="/res/**" location="/res/" />
<bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    <property name="prefix" value="/WEB-INF/jsp/" />
    <property name="suffix" value=".jsp" />
</bean>
рüффп
  • 5,172
  • 34
  • 67
  • 113
hguser
  • 35,079
  • 54
  • 159
  • 293

1 Answers1

1

Try adding in your resource message properties file a property with typeMismatch key.

In a generic way for any typeMismatch error:

typeMismatch=This is a not valid type

or more specific, to a concrete property:

typeMismatch.person.age=This is a not valid a type

This will prevent Spring to throw an exception and corresponding message will be added to your errors.

Hope this helps.

Update:

You have to add this bean in your servlet-context.xml:

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"
        p:basename="/WEB-INF/messages/validation" />

And add file validation.properties in /WEB-INF/messages folder with values mentioned above (typeMismatch...).

jelies
  • 9,110
  • 5
  • 50
  • 65
  • hi,jelies,it works.however,I found that the typemismatch does not prevent the validation. I mean if there a validator on the model,even the type does not match,the validation will work. then,in the form,the validation message and typemismatch message will display at the same time. – hguser Sep 04 '12 at 13:43
  • But how is possible to validate some property if type doesn't match? I didn't remember this behaviour when I used this... – jelies Sep 04 '12 at 14:39
  • http://stackoverflow.com/questions/12244639/spring-mvc-nested-model-validation。 note the project.manager.id. if a string is submitted to server,what I said will happe – hguser Sep 04 '12 at 14:43