问题
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.
回答1:
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/
回答2:
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:
to define correct path
WEB-INF/i18n/messagesto your property file inmessageSourcebean;to configure
LocalValidatorFactoryBeanin the config file;to inject the declared validator in your controller and use it.
As shown here.
来源:https://stackoverflow.com/questions/31223859/not-able-to-print-message-from-properties-file-using-size-annotation-using-sprin