[英]Spring Rest Controller PUT method request body validation?
Here is what i have in my controller. 这是我控制器中的物品。
@RequestMapping(value = "/accountholders/{cardHolderId}/cards/{cardId}", produces = "application/json; charset=utf-8", consumes = "application/json", method = RequestMethod.PUT)
@ResponseBody
public CardVO putCard(@PathVariable("cardHolderId") final String cardHolderId,
@PathVariable("cardId") final String cardId, @RequestBody final RequestVO requestVO) {
if (!Pattern.matches("\\d+", cardHolderId) || !Pattern.matches("\\d+", cardId)) {
throw new InvalidDataFormatException();
}
final String requestTimeStamp = DateUtil.getUTCDate();
iCardService.updateCardInfo(cardId, requestVO.isActive());
final CardVO jsonObj = iCardService.getCardHolderCardInfo(cardHolderId, cardId, requestTimeStamp);
return jsonObj;
}
This is the request body bean:- 这是请求主体bean:-
public class RequestVO {
private boolean active;
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
The issue that I am having is when i sent the request body as {"acttttt":true} the active is set to false it updates the cardinfo with false. 我遇到的问题是,当我将请求正文发送为{“ acttttt”:true}时,active设置为false,它将cardinfo更新为false。 Whatever wrong key value i sent the active is considered as false. 我发送给活动设备的任何错误的键值都被认为是错误的。 How would I handle this is their a way. 我将如何处理这是他们的一种方式。 Every other scenario is handled by spring with a 404. Spring会使用404处理所有其他情况。
Any help or suggestion is appreciated. 任何帮助或建议,表示赞赏。
Because the default value for primitive boolean
is false
. 因为原始boolean
值的默认值为false
。 Use its corresponding Wrapper, Boolean
, instead: 使用其对应的Wrapper Boolean
:
public class RequestVO {
private Boolean active;
// getters and setters
}
If the active
value is required, you can also add validation annotations like NotNull
: 如果需要active
值,则还可以添加验证注释,例如NotNull
:
public class RequestVO {
@NotNull
private Boolean active;
// getters and setters
}
Then use Valid
annotation paired with RequestBody
annotation to trigger automatic validation process. 然后,将Valid
注释与RequestBody
注释配对使用,以触发自动验证过程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.