编辑2因为您没有模型属性,所以需要使用实现错误的具体类。
BeanPropertyBindingResult
就是这样。
您可以使用
BeanPropertyBindingResult
如下所示
@RequestMapping(value = "/publicar", method = { RequestMethod.GET, RequestMethod.POST }, produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody
public ApiPubPortalPublicarOut publicar(@RequestParam(value = PARAM_XML) String xml, Locale locale) {
//This object is my return, it creates an XML with the validation.
ApiPubPortalPublicarOut xmlTaxOut = new ApiPubPortalPublicarOut();
//validate incoming xml is empty
if ((xml == null) || (xml.length() == 0)) {
xmlTaxOut.setDescription("xml is Empty!");
return xmlTaxOut;
}else{
try{
//I transform the xml into an object
JAXBContext jc = JAXBContext.newInstance(ApiPubPortalPublicarPortal.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
StreamSource streamSource = new StreamSource(new StringReader(xmlEntrada));
JAXBElement<ApiPubPortalPublicarPortal> je = unmarshaller.unmarshal(streamSource, ApiPubPortalPublicarPortal.class);
// Using concrete implementation of error interface
BeanPropertyBindingResult result = new BeanPropertyBindingResult(je.getValue(), "apiPubPortal");
//Here is the validation method.
parsingPublicacion(je.getValue(), result, locale);
if(result.hasErrors()){
xmlTaxOut.setDescription(result.getAllErrors().toString());
return xmlTaxOut;
}
}catch(Exception){
xmlTaxOut.setDescription("Error parsing!");
return xmlTaxOut;
}
}
}
编辑1
您也可以将错误接口用作方法参数。Spring仍将填充一个实现。
使用
BindigResults
像
方法参数
并将其用于
错误
。Spring将自动为您填充一个实现。
@RequestMapping(value = "/publicar", method = { RequestMethod.GET, RequestMethod.POST }, produces = MediaType.APPLICATION_XML_VALUE)
@ResponseBody
public ApiPubPortalPublicarOut publicar(@RequestParam(value = PARAM_XML) String xml,
BindingResult result, Locale locale) {
//This object is my return, it creates an XML with the validation.
ApiPubPortalPublicarOut xmlTaxOut = new ApiPubPortalPublicarOut();
// Use BindingResult in places of erros
}
绑定结果
扩展错误,因此您将在其中具有错误功能。
https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-arguments