Spring初始化控制器类中的Errors接口

时间:2018-05-16 09:51:37

标签: java spring model-view-controller

我遇到了一些我在项目中运行的验证问题。我正在尝试验证我在控制器中创建的对象中的一些参数,首先收到一个String。

@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();
            Errors result = null; //Here is the problem

            //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);

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

这是我的控制器,你可以看到我尝试将我的字符串转换为一个对象,然后我调用方法parsingPublicacion来进行验证。

主要问题是我无法初始化Errors参数,因为它是一个界面,任何人都知道如何管理此验证?

这是mi验证方法。

private void parsingPublicacion(ApiPubPortalPublicarPortal portalPublicado,  Errors e, Locale locale) {
    ApiPubPortalPublicarPortal pubPortal = portalPublicado;

    ValidationUtils.rejectIfEmptyOrWhitespace(e, "name", "name.empty"));
    if (pubPortal.getNombre().length() > 50){
        e.rejectValue("name", "name.oversize");
    }

    ValidationUtils.rejectIfEmptyOrWhitespace(e, "idLanguage.empty");
    if ((pubPortal.getIdPortal() == 0)){
        e.rejectValue("idLanguage", "idLanguage.zero"));
    }

}

我无法从方法中调用错误,因为我只允许在控制器中调用特定的参数。

2 个答案:

答案 0 :(得分:1)

  

编辑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   您也可以使用Error接口作为方法参数。 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


        }

BindingResult 扩展了错误,因此您将拥有错误的功能。

https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-arguments

答案 1 :(得分:0)

You can Binding Result & FieldErrors instead of Errors. Please find the below code.

private void parsingPublicacion(ApiPubPortalPublicarPortal portalPublicado,  BindingResult bindingResult, Locale locale) {
    ApiPubPortalPublicarPortal pubPortal = portalPublicado;
    String[] codes = {"errorCode"};
    ValidationUtils.rejectIfEmptyOrWhitespace(e, "name", "name.empty"));
    if (pubPortal.getNombre().length() > 50){
        e.rejectValue("name", "name.oversize");
        bindingResult.addError(new FieldError(Yourclass.getSimpleName(),"Name", pubPortal.getNombre(), false , codes , null , "name.oversize"));
    }

    ValidationUtils.rejectIfEmptyOrWhitespace(e, "idLanguage.empty");
    if ((pubPortal.getIdPortal() == 0)){
        e.rejectValue("idLanguage", "idLanguage.zero"));
        bindingResult.addError(new `enter code here`FieldError(Yourclass.getSimpleName(),"idLanguage", pubPortal.getIdPortal(), false , codes , null , "idLanguage.zero"));
    }

}