代码之家  ›  专栏  ›  技术社区  ›  Kordh Rufan

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

  •  0
  • Kordh Rufan  · 技术社区  · 6 年前

    我在项目中运行的一些验证有问题。我试图验证我在控制器中创建的对象中的一些参数,首先接收一个字符串。

    @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 回复  |  直到 6 年前
        1
  •  1
  •   mirmdasif    6 年前

    编辑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

        2
  •  0
  •   Srikanth Pasupuleti    6 年前
    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"));
        }
    
    }