【问题标题】:Spring XML databinding not in ControllerSpring XML 数据绑定不在控制器中
【发布时间】:2018-05-17 18:10:46
【问题描述】:

我想将验证逻辑从 Spring 控制器移动到 ServletFilter,并且我想在 ServletFilter 中实现 DataBinding,这样我就可以将我的 XML 数据自动解析到我的 POJO 中,并且我可以在我的过滤器中使用 BindingResult 对象。

这可能吗,或者我只能在我的控制器中利用 DataBinding 和 BindingResult?

不管怎样,这是我的控制器的请求映射:

@RequestMapping(produces = MediaType.APPLICATION_XML_VALUE, consumes = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value="Verifica Ordine")
public Object listaVerificaOrdine(@Valid @RequestBody VerificaOrdineRequestModel requestModel, BindingResult result) throws RemoteException{
  if(result.hasErrors()){
    return "Errori: " + result.toString();
  }
  ...
}

【问题讨论】:

    标签: java xml spring data-binding controller


    【解决方案1】:

    通过使用我们的 Spring Controller 正在使用的相同库,可以在 Controller 之外使用 Databinding 和 JSR-303 验证(但在 Controller 中,它们会导致“隐藏”在 Spring 框架后面)。特别是:

    1. 对于来自 XML 的数据绑定,我使用 JAXB 库
    2. 对于 JSR-303 验证,我使用 javax.validation 库。

    让我们看看如何做到这一点:

    try {
            Object model = JAXB.unmarshal(new StringReader(xmlString), classe);
            ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
            Validator validator = factory.getValidator();
            Set<ConstraintViolation<Object>> violations = validator.validate(model);
    
            for(ConstraintViolation violation : violations){
                responseError.append("Errore al percorso '" + violation.getPropertyPath() +"': ");
                responseError.append(" il valore trovato e' '" + violation.getInvalidValue() + "' ");
                responseError.append(", mentre il valore atteso deve rispettare il seguente criterio: '" + violation.getMessage() + "'. \n\n");
            }
        } catch (Exception e) {
            responseError.append("Eccezione nel parsing dell'oggetto: " + e.toString() + ". Probabilmente il file XML di input non e' ben formato. Controllare i tag di apertura e di chiusura.  \n\n");
        }
    

    【讨论】:

      猜你喜欢
      • 2018-09-29
      • 2018-06-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      相关资源
      最近更新 更多