Spring Rest Controller PUT方法请求身体验证?

时间:2016-01-18 18:48:55

标签: java json spring spring-boot spring-restcontroller

这是我在控制器中的内容。

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

这是请求正文bean: -

public class RequestVO {

    private boolean active;

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }

我遇到的问题是当我发送请求正文时 {“acttttt”:true} active设置为false,用false更新cardinfo。无论我发送了什么错误的键值,都认为是活动的。我怎么处理这是他们的方式。每个其他场景都由spring处理404。

感谢任何帮助或建议。

1 个答案:

答案 0 :(得分:2)

因为原始boolean的默认值为false。使用相应的包装器Boolean代替:

public class RequestVO {

    private Boolean active;

    // getters and setters
}

如果需要active值,您还可以添加NotNull等验证注释:

public class RequestVO {

    @NotNull
    private Boolean active;

    // getters and setters
}

然后使用与Valid注释配对的RequestBody注释来触发自动验证过程。