我有一个返回 JSON 的控制器。它采用一个表单,通过 spring 注释验证自己。我可以从 BindingResult 获取 FieldError 列表,但它们不包含 JSP 将在标记中显示的文本。如何获取错误文本以 JSON 格式发回?
@RequestMapping(method = RequestMethod.POST)
public
@ResponseBody
JSONResponse submit(@Valid AnswerForm answerForm, BindingResult result, Model model, HttpServletRequest request, HttpServletResponse response) {
if (result.hasErrors()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
JSONResponse r = new JSONResponse();
r.setStatus(JSONResponseStatus.ERROR);
//HOW DO I GET ERROR MESSAGES OUT OF BindingResult???
} else {
JSONResponse r = new JSONResponse();
r.setStatus(JSONResponseStatus.OK);
return r;
}
}
JSONREsponse 类只是一个 POJO
public class JSONResponse implements Serializable {
private JSONResponseStatus status;
private String error;
private Map<String,String> errors;
private Map<String,Object> data;
...getters and setters...
}
调用 BindingResult.getAllErrors() 返回一个 FieldError 对象数组,但它没有实际错误。