我有这个类,字段“nome”不能为空
public class Utente {
......
@NotEmpty
@Size(min=2, max=30)
private String nome;
.......
}
用户填写并发送表格后,我称之为
@RequestMapping("/formSent")
public String formSentMethod(Model model, @Valid Utente utente, BindingResult result){
.....
}
我使用这个普通代码在Eclipse的控制台中打印错误,放在formSentMethod方法中。
@RequestMapping("/formSent")
public String formSentMethod(Model model, @Valid Utente utente, BindingResult result){
.....
for(ObjectError errore : result.getAllErrors()){
System.out.println(errore.getDefaultMessage());
}
.....
}
到目前为止,当用户未填写“nome”字段时,我收到默认错误消息“可能不为空”。
我试图通过使用名为messages.properties的属性文件来自定义该消息,我将其置于WEB-INF / classes下,如您在此图中所见
我编写的messages.properties内部
NotEmpty.utente.nome = Il nome è obbligatorio
在我的XXX-servlet.xml中,我以这种方式“调用”属性文件
<bean class="org.springframework.context.support.ResourceBundleMessageSource" id="messageSource">
<property name="basename" value="messages" />
</bean>
<mvc:annotation-driven />
由于它不起作用我甚至尝试以这种方式编辑basename值
<property name="basename" value="WEB-INF/Classes/messages" />
但它也不起作用。
我继续收到默认错误消息,而不是我的自定义消息“Ilnomeèobbligatorio”。可能我在我的属性文件中写的不正确。我做错了什么?
答案 0 :(得分:2)
message.properties不引用类和字段,而是引用表单名称和字段。例如在这个html中:
<form:form method="POST" commandName="utente" action="customer/signup">
<form:errors path="*" cssClass="errorblock" element="div" />
<table>
<tr>
<td>Customer Name :</td>
<td><form:input path="nome" /></td>
<td><form:errors path="nome" cssClass="error" /></td>
</tr>
<tr>
<td>Customer Age :</td>
<td><form:input path="age" /></td>
<td><form:errors path="age" cssClass="error" /></td>
</tr>
<tr>
<td colspan="3"><input type="submit" /></td>
</tr>
</table>
</form:form>
NotNull.utente.nome
将是正确的,因为表单utente
包含字段nome
。重要的是,它不是基于类,而是基于html中的路径。
要从控制器访问国际化,您需要MessageSource
bean,并使用bean来获得国际化。
以下是从here访问控制器中的国际化消息的示例:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="ValidationMessages"/>
</bean>
在控制器中注入MessageSource
实例
@Autowired
private MessageSource messageSource;
要获得您的信息,请执行以下操作
for (Object object : bindingResult.getAllErrors()) {
if(object instanceof FieldError) {
FieldError fieldError = (FieldError) object;
/**
* Use null as second parameter if you do not use i18n (internationalization)
*/
String message = messageSource.getMessage(fieldError, null);
}
}
答案 1 :(得分:0)
根据您的配置,我认为邮件应该放在classes
内,但是要提升一级。
您还可以创建一个绝对路径:
/ WEB-INF /类/消息
或一级升级
/ WEB-INF /消息
此外,请记住,使用此配置,您不会设置默认编码,这可能会导致一些问题,我建议将属性defaultEncoding
设置为UTF-8