使用@Valid在spring中验证Request主体

时间:2016-08-23 12:13:47

标签: java spring validation

我想验证属性长度的JSON对象。我正在使用@Size注释来指定最大长度,如下所示。

@JsonRootName("question")
public class QuestionJson {
    @JsonProperty(value = "id", required = false)
    private Long id;
    @JsonProperty(value = "text", required = true)
    private String label;
    @JsonProperty(value = "answers", required = true)
    private List<AnswerJson> answers;

}

@JsonRootName("answer")
public class AnswerJson {
@JsonProperty(value = "id", required = false)
private Long id;
@JsonProperty(value = "type", required = true)
private String type;

@JsonProperty(value = "label", required = true)
@Size(message = "size should not be long", max = 10)
private String label;
}

我在控制器中的请求映射如下:

@RequestMapping(value = "/api/answer", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public AnswerJson createQuestion(@RequestHeader(HttpHeaders.AUTHORIZATION) final String authorizationHeader, @Valid @RequestBody final QuestionJson questionJson) {
    // some code here....
    return answer;

}

更新:验证适用于外部元素,例如。在我的情况下text但在嵌套列表上失败。

1 个答案:

答案 0 :(得分:0)

找到解决方案。我们需要在嵌套对象声明之前添加DECLARE CURSOR cEmploee IS SELECT * FROM g_emploees; iTotal INTEGER := 0; iCount INTEGER := 0; BEGIN SELECT COUNT(*) FROM g_emploees INTO iTotal; FOR rLine IN cEmploee loop dbms_output.put_line('Porcessed['||rLine.id||']: '|| ((iCount/iTotal)*100) || '%') iCount := iCount + 1; END LOOP; END; 注释。例如

@Valid