0

I am completely new to Spring MVC. I have a Student class with below annotation

@Size(min=2, max=10 )
public String studentHobby;

and a StudentController class:

@RequestMapping("admissionSuccess.html")
public ModelAndView admissionSuccess(@Valid @ModelAttribute("student") Student student,BindingResult result)
{

    if(result.hasErrors())
    {
        ModelAndView model=new ModelAndView("admissionForm");
        return model;
    }
    ModelAndView model=new ModelAndView("admissionSuccess");
    model.addObject("student",student);
    return model;
}

and studentmessages.properties:

Size.student.studentHobby=please enter a value for studenthobby  between 2 and 10;

and spring-servlet.xml file :

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/studentmessages/"></property>
</bean>

I am not able to print the message from properties file, I am getting the default message. Please tell me whether there is something wrong with the code.

2 Answers 2

0

How is your directory structure? It looks like you set the basename of yout ReloadableResourceBundle to match your property filename. Instead of that it must match the folder where you put your message files. And rename studentmessages.properties to ValidationMessages.properties (the default resource bundle for validation messages).

Like this:

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/messages/"></property>
</bean>

And add this to your configuration xml:

<bean id=”validator” class=”org.springframework.validation.beanvalidation.LocalValidatorFactoryBean” >
    <property name=”validationMessageSource” ref=”messageSource”/>
</bean>

Directory structure:

...
   |_ WEB-INF
         |_ messages
               |_ ValidationMessages.properties

And you should specify in the property of your model which message should be used on validation (like Igor Patsyan said). Like this:

@Size(min=2, max=10, message="Size.student.studentHobby")
public String studentHobby;

Reference: http://www.silverbaytech.com/2013/04/16/custom-messages-in-spring-validation/

0

You need to add an attribute message to the annotation @Size:

@Size(min=2, max=10, message = 'Size.student.studentHobby' )

If you don't define this attribute, a message will be genereted automatically:

"size must be between 2 and 10"

And also you need:

  1. to define correct path WEB-INF/i18n/messages to your property file in messageSource bean;

  2. to configure LocalValidatorFactoryBean in the config file;

  3. to inject the declared validator in your controller and use it.

As shown here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.