我昨天工作过,然后做了一些工作,现在我一直试图修复它几个小时,但我无法再继续工作了。验证邮件没有从邮件属性文件中获取到Spring中
我有一个包含<form:form>
的Spring MVC应用程序,当用户输入错误信息时,我想从.properties文件中显示自定义错误消息(<form:errors>
)。 JSR-303注释中定义了什么“错误”。从表单
摘录:
<form:form method="post" action="adduserprofile" modelAttribute="bindableUserProfile">
<table>
<tr>
<td><form:label path="firstName">Voornaam</form:label></td>
<td>
<form:input path="firstName"/>
<form:errors path="firstName" />
</td>
</tr>
<tr>
<td><form:label path="lastName">Achternaam</form:label></td>
<td>
<form:input path="lastName"/>
<form:errors path="lastName" />
</td>
</tr>
从BindableUserProfile摘录:从控制器
@NotNull
@Size(min = 3, max = 40, message="{errors.requiredfield}")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
@NotNull
@Size(min = 3, max = 40, message="errors.requiredfield")
public String getLastName() {
return lastName;
}
摘录:
@RequestMapping(value = "/edit/{userProfileId}", method = RequestMethod.GET)
public String createOrUpdate(@PathVariable Long userProfileId, Model model) {
if (model.containsAttribute("bindableUserProfile")) {
model.addAttribute("userProfile", model.asMap().get("bindableUserProfile"));
} else {
UserProfile profile = userProfileService.findById(userProfileId);
if (profile != null) {
model.addAttribute(new BindableUserProfile(profile));
} else {
model.addAttribute(new BindableUserProfile());
}
}
model.addAttribute("includeFile", "forms/userprofileform.jsp");
return "main";
}
@RequestMapping(value = "/adduserprofile", method = RequestMethod.POST)
public String addUserProfile(@Valid BindableUserProfile userProfile, BindingResult result, Model model) {
if (result.hasErrors()) {
return createOrUpdate(null, model);
}
UserProfile profile = userProfile.asUserProfile();
userProfileService.addUserProfile(profile);
return "redirect:/userprofile";
}
从应用程序的context.xml摘录
<bean name="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="messages/messages"/>
</bean>
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource">
<ref bean="messageSource"/>
</property>
</bean>
在资源/消息中我有两个文件,messages_en.properties和messages_nl.properties。两者具有相同的,简单的内容:
errors.requiredfield=This field is required!!!
- 当我提交表单用空的名字我可以在控制器方法“addUserProfile()”的错误确实发现看到的。
- 当我用空的名字提交表单时,在字段旁边显示了消息标识符,即在姓氏的情况下字面文本“errors.requiredfield”或“{errors.requiredfield}”。
- 当我将消息属性值更改为“Foo”而不是“Foo”时显示为错误消息。所以错误机制本身似乎很好。
- application-context.xml中的messageSource bean必须是正确的,因为它表示在更改基本名称时找不到属性文件。
- 空输入未被NotNull注释捕获。 Spring将空输入视为空字符串,而不是空。
所以,看起来属性文件被找到并且验证注解被正确处理,但是Spring并不理解它必须用属性文件中的消息替换消息键。
你能从.properties文件中设置min和max吗? – luksmir 2013-10-31 12:18:43