gpt4 book ai didi

java - 如何为在 spring 中抛出 ny @Valid 注释的错误消息创建属性文件

转载 作者:行者123 更新时间:2023-11-30 09:02:48 25 4
gpt4 key购买 nike

我有这个类,其中“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”时,我收到默认错误消息“may not be empty”。

我尝试通过使用一个名为 messages.properties 的属性文件来自定义该消息,我将其放在 WEB-INF/classes 下,如您在此图片中所见 enter image description here

我写的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" />

但效果不佳。

我一直收到默认错误消息,而不是我的自定义消息“Il nome è obbligatorio”。可能我在我的属性文件中写的不正确。我做错了什么?

最佳答案

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 中的路径

要从 Controller 访问国际化,您需要 MessageSource bean,并使用该 bean 来获取国际化。

这是取自 here 的示例在 Controller 中访问国际化消息:

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames" value="ValidationMessages"/>
</bean>

将您的 MessageSource 实例注入(inject)到您的 Controller 中

@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);
}
}

关于java - 如何为在 spring 中抛出 ny @Valid 注释的错误消息创建属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25870038/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com