如何使用spring在JSR 303中仅为多行显示一条验证错误消息?

时间:2014-05-22 09:02:42

标签: java spring validation spring-mvc

有一个有多行的网格。每行都有两个相同的文本字段。我正在使用JSR 303来验证这些字段,验证正在进行中。然而,问题是显示了多个错误消息(每行一个),这是不可取的。是否有办法为每个字段显示所有行的一条错误消息?

public ModelAndView insert(@Valid @ModelAttribute("proposalwiseselectionform")ProposalWiseSelectionForm proposalwiseselectionformobj,
                               BindingResult result,
                               HttpServletRequest request, HttpServletResponse response) {
        if (result.hasErrors()) {
            if (formBeanObj == null) {
                formBeanObj = proposalwiseselectionformobj;
            }
            mav = new ModelAndView("proposalwiseselection");

            mav.addObject("proposalwiseselectionform", formBeanObj);
        }
    }




public class ProposalWiseSelectionForm {
private String txtLineOfBusiness;
private String txtProduct;
private String btn;
private String clickedGo="N";   
private List arrLineOfBusiness=new ArrayList();
private List arrProduct=new ArrayList();
@Valid
private ArrayList documentList=initiateDocumentList();
private String txtPageMode="I";
private String enableDiscardBtn="N";
private String enableInsertBtn="N";

public ArrayList initiateDocumentList(){
    ArrayList arr=new ArrayList();
    for(int i=0; i<1;i++){
      arr.add(new ProposalWiseSelectionChildForm(i));
    }
    return arr;
  }
}



public class ProposalWiseSelectionChildForm {

private String numProposalWiseSelection;        
private String txtTransactionType;
private String txtTransactionTypeCode;  

@NotEmpty(message="Transaction Type cannot be empty")
private String txtTransactionDesc;

@NotEmpty(message="Document Type cannot be empty")
private String txtPolicyDocument;
private String ynChkBox="0";

}

JSP片段如下,

form:form action="/proposalwiseselection" commandName="proposalwiseselectionform" method="POST" id="proposalwiseselection"/  
form:errors path="*" cssClass="errorblock" element="div"/
form:input path="documentList[${docStatus.index}].txtTransactionDesc"  cssClass="noneditableinputbox" size="40" onkeydown="transactionTypeLOV(event.keyCode,this)" readonly="true" title="Press F2 to get transaction type list" /
form:hidden path="documentList[${docStatus.index}].txtTransactionTypeCode"/
form:input path="documentList[${docStatus.index}].txtPolicyDocument"  cssClass="noneditableinputbox" size="40"  readonly="true"/
form:hidden path="documentList[${docStatus.index}].numPolicyDocumentCode"/

1 个答案:

答案 0 :(得分:0)

虽然以下解决方案非常粗糙,但它会执行您需要的功能。 你可以轻松地使工作变得更具可读性并坚持使用Spring主体,但是我只是想说明你可以做些什么样的事情。

首先,你需要先从Spring获得Validator

@Autowired
Validaror validator;

接下来,您需要删除@Valid注释并自行执行验证。

这意味着您的方法将如下所示:

public ModelAndView insert(@ModelAttribute("proposalwiseselectionform")ProposalWiseSelectionForm proposalwiseselectionformobj,
                               BindingResult result,
                               HttpServletRequest request, HttpServletResponse response)

{
        validate(bindingResult);
        if (result.hasErrors()) {
            if (formBeanObj == null) {
                formBeanObj = proposalwiseselectionformobj;
            }
            mav = new ModelAndView("proposalwiseselection");

            mav.addObject("proposalwiseselectionform", formBeanObj);
        }
}

最后,验证方法如下所示:

private void validate(BindingResult bindingResult) {

    final BindingResult intermediateBindingResult = new BeanPropertyBindingResult(bindingResult.getTarget(), bindingResult.getObjectName()) ;
    validator.validate(bindingResult.getTarget(), intermediateBindingResult);

    final List<FieldError> originalFieldErrors = intermediateBindingResult.getFieldErrors();
    final Set<String> alreadyAddedFieldNames = new HashSet<>();
    final List<FieldError> distinctFieldErrors = new ArrayList<>();
    for (FieldError fieldError : originalFieldErrors) {
        if(alreadyAddedFieldNames.contains(fieldError.getField())) {
            continue;
        }

        distinctFieldErrors.add(fieldError);
        alreadyAddedFieldNames.add(fieldError.getField());
    }

    for (FieldError distinctFieldError : distinctFieldErrors) {
        bindingResult.addError(distinctFieldError);
    }
}

上面的代码是将常规验证存储到中间绑定结果中,并将循环存储在所有FieldError上,并且每个字段只添加第一个。