gpt4 book ai didi

java - ValidationMessages.properties 未通过 BindException 解析

转载 作者:行者123 更新时间:2023-11-30 07:59:26 24 4
gpt4 key购买 nike

我可能只是做得不对,但就是这样。

我有一个 Spring Boot 应用程序,其中添加了 Hibernate Validator,并且有一个如下所示的命令对象:

public class SignupCommand {

@Pattern(regexp = "^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$")
private String someDate;

// getters/setters omitted for brevity

}

Controller 中的 @RequestMapping 如下所示:

@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public AuthToken signUp(@Valid @RequestBody SignupCommand signupCommand,
BindingResult bindingResult) throws BindException {
if (bindingResult.hasErrors()) {
throw new BindException(bindingResult);
}
return accountService.signUp(signupCommand);
}

这会返回我期望的 JSON,带有错误代码,如下所示:

{
"timestamp" : 1440256315621,
"status" : 400,
"error" : "Bad Request",
"exception" : "org.springframework.validation.BindException",
"errors" : [ {
"codes" : [ "Pattern.signupCommand.someDate", "Pattern.someDate", "Pattern.java.lang.String", "Pattern" ],
"arguments" : [ {
"codes" : [ "signupCommand.someDate", "someDate" ],
"arguments" : null,
"defaultMessage" : "someDate",
"code" : "someDate"
}, [ ], "^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$" ],
"defaultMessage" : "must match \"^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$\"",
"objectName" : "signupCommand",
"field" : "someDate",
"rejectedValue" : "02-16-2015",
"bindingFailure" : false,
"code" : "Pattern"
} ],
"message" : "Validation failed for object='signupCommand'. Error count: 1",
"path" : "/api/signup"
}

这就是我的问题发生的地方。我尝试将以下内容放入类路径根部的 messages.propertiesValidationMessages.properties 中(在 src/main/resources 中) )没有任何运气:

Pattern.signupCommand.someDate=Please enter a valid date in the format MM-DD-YYYY.

我想我只是对 Spring 如何与 Hibernate Validator 结合进行消息解析没有足够的了解。如有任何帮助,我们将不胜感激!

更新

我决定将 message="{mymessage}" 添加到 @Pattern 中,并在两个文件中添加 mymessage=Some message看看正在使用哪一个。当像 ValidationMessages.properties 文件中那样显式定义消息时,它看起来能够解析消息。

最佳答案

如果您使用javax.validation.constraints.Pattern.message=...作为您的消息键,该值将用于所有模式验证错误消息。这不太可能是您想要的,因为并非所有模式都适用于日期!

采用 @Pattern(..., message="dateValidationMessage") 的方法并使用 dateValidationMesssage=...因为您的消息键将起作用。

关于java - ValidationMessages.properties 未通过 BindException 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32158233/

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