我有一个返回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对象的数组,但没有实际错误。
免责声明:我仍然不使用Spring-MVC 3.0
但是我认为Spring 2.5使用的相同方法可以满足您的需求
for (Object object : bindingResult.getAllErrors()) { if(object instanceof FieldError) { FieldError fieldError = (FieldError) object; System.out.println(fieldError.getCode()); } if(object instanceof ObjectError) { ObjectError objectError = (ObjectError) object; System.out.println(objectError.getCode()); } }
希望对您有用
更新
如果要获取资源包提供的消息,则需要一个注册的messageSource实例(它 必须 称为messageSource)
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames" value="ValidationMessages"/> </bean>
将您的MessageSource实例注入视图中
@Autowired private MessageSource messageSource;
要获取您的消息,请执行以下操作
for (Object object : bindingResult.getAllErrors()) { if(object instanceof FieldError) { FieldError fieldError = (FieldError) object; /** * Use null as second parameter if you do not use i18n (internationalization) */ String message = messageSource.getMessage(fieldError, null); } }
您的验证器应该看起来像
/** * Use null as fourth parameter if you do not want a default message */ errors.rejectValue("<FIELD_NAME_GOES_HERE>", "answerform.questionId.invalid", new Object [] {"123"}, null);