英文:
Springboot [2.1.6.RELEASE] - Disable autocorrect input dates
问题
我有一个简单的问题。
如果我发送一个带有以下日期参数的请求体(如下),springboot会自动将其转换为1991年5月1日,我想禁用这个功能。我想要抛出一个异常来告诉客户端,这不是一个有效的日期。这可能吗?
我的请求体:
{
"gender": "MALE",
"firstname": "XXX",
"lastname": "XXX",
"birthday": "1991-04-31"
}
我的 WebRequestController:
public @ResponseBody void updateUser(@PathVariable Long userId, @Valid @RequestBody UserUpdateIDTO userDTO) throws UserNotFoundException, ValidationException {
userService.updateUser(userId, userDTO); // userDTO 得到了1991年5月1日
}
英文:
i got a simple problem.
If i sent a body with following date parameters (below) springboot automatically convert it to the 1st of May 1991 and i want to disable it. I would like to throw an exception to tell the client, that is not a valid date. Is that possible?
My sent body:
{
"gender": "MALE",
"firstname": "XXX",
"lastname": "XXX",
"birthday": "1991-04-31"
}
My WebRequestController:
public @ResponseBody void updateUser (@PathVariable Long userId, @Valid @RequestBody UserUpdateIDTO userDTO) throws UserNotFoundException, ValidationException {
userService.updateUser(userId, userDTO); // userDTO got the 1st may 1991
}
答案1
得分: 1
你可以进行诸如以下验证:
@JsonDeserialize(using = Deserializer.class)
@JsonSerialize(using = Serializer.class)
@JsonFormat(pattern = "yyyy-MM-dd")
private Date begin_date;
看起来这可能不够,因为你不仅要检查格式,还要进行验证。所以最好还是使用一个反序列化器。为此,你需要像这样更改核心部分:
public class Deserializer extends JsonDeserializer<Date>{
}
你可以在这里查看如何验证日期:https://www.baeldung.com/java-string-valid-date,基于此,你还可以抛出错误。
顺便问一下,我们能看到你的 UserUpdateIDTO 吗?
英文:
Hello you can do validation such as;
@JsonDeserialize(using = Deserializer.class)
@JsonSerialize(using = Serializer.class)
@JsonFormat(pattern = "yyyy-MM-dd")
private Date begin_date;
It seems like this will not be enough because you not only check format but want to validate. So you better do a deserializer. To do that you need to change the core like this.
public class Deserializer extends JsonDerializer<Date>{
}
https://www.baeldung.com/java-string-valid-date from here you can check how to validate date and based on that you can throw error as well.
By the way can we see your -> UserUpdateIDTO
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论