我正在尝试在资源文件中定义错误消息,但我似乎无法加载它们,因此我可以在 Controller 中使用它们。
我的servlet-context.xml文件:
<beans:bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<beans:property name="basename" value="classpath:messages" />
</beans:bean>
我的表单:
public class LoginForm {
@NotEmpty
private String username;
// getters and setters
}
我的messages.properties文件(位于我的源文件夹的根目录中,因此它被编译到我的类文件夹的根目录中):
NotEmpty.loginForm.username=test1
NotEmpty.username=test2
NotEmpty.java.lang.String=test3
NotEmpty=test4
我的 Controller :
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(@Valid LoginForm form, BindingResult result) {
if (result.getFieldErrors().size() > 0) {
FieldError firstError = result.getFieldErrors().get(0);
System.out.println(firstError.getDefaultMessage());
}
// ...
}
但是,getDefaultMessage
调用的输出从来都不是我在资源文件中定义的内容!它始终可能不为空
(默认值)。
我在上下文文件中尝试了各种不同的条目,但似乎没有加载资源文件。我做错了什么?
最佳答案
根据这个documentation ,您所需要做的就是将一个名为 ValidationMessages.properties
的属性文件放在项目类路径的根目录中。
然后您可以使用以下格式添加属性
org.hibernate.validator.constraints.NotEmpty.message=Default message, can not be empty
NotEmpty.ClassName.fieldName=fieldName can not be empty.
其中 ClassName
是您的类的名称,fieldName
是该类的字段名称。
您可能需要进行一些配置才能设置正确的 MessageInterpolator
,但我认为默认配置即可满足您的需要。
关于java - Spring MVC 表单验证消息未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18339568/