1

这是我的验证方法 -

@Override
  public void validate() {
    errors = new HashMap<String, String>();
    if(StringUtil.isBlank(examCode)){
      errors.put("examCode", "Exam code is required");
    }
    if(StringUtil.isBlank(strPaperType)){
      errors.put("paperType", "Paper Type is required");
    }else{
      paperType = PaperType.getPaperTypeByValue(strPaperType);
      if(paperType == null){
        errors.put("paperType", "A valid Paper Type is required");
      }
      if(paperType.equals(PaperType.PRACTICE)){
        if(topicId ==null){
          errors.put("topicId", "Topic Id is required");
        }
      }
    }
    if(StringUtil.isBlank(instructions)){
      errors.put("instructions", "Paper Instructions are required");
    }
  }

'errors' 是我自己在操作中定义的地图。我没有向“fieldErrors”添加任何错误。如果我调试“fieldErrors”,甚至在输入“验证”方法之前发生的事情,我会看到以下两个条目 -

{"id":["Invalid field value for field \"id\"."],"topicId":["Invalid field value for field \"topicId\"."]}

我不知道他们是从哪里添加的。这是我的struts conf。

<package name="api" extends="json-default" namespace="/api">
    <action name="paper" class="paperApiAction">
      <result name="json" type="json">
        <param name="root">responseDto</param>
      </result>
      <result name="input" type="json">
        <param name="root">fieldErrors</param>
      </result>
    </action>
  </package>

需要帮助。谢谢

4

2 回答 2

2

conversionError”拦截器会接受类型转换错误并将它们放入fieldErrors. 有些用例更容易将其从堆栈中取出;我不确定这是否是其中之一。

为什么要复制fieldErrors地图?即使您只是想在自己的 DTO 中使用地图,为什么不使用现有的验证机制呢?区别很小,而且更灵活一些。然后,您可以将纸张类型验证构建到外部化的业务逻辑中,并简化对其和操作的测试。


不相关,但由于缺少空格,我发现您的代码难以阅读。一个天真的重构:

@Override
public void validate() {
    errors = new HashMap<String, String>();

    if (StringUtil.isBlank(examCode)) {
        errors.put("examCode", "Exam code is required");
    }

    if (StringUtil.isBlank(instructions)) {
      errors.put("instructions", "Paper Instructions are required");
    }

    if (StringUtil.isBlank(strPaperType)) {
        errors.put("paperType", "Paper Type is required");
    } else {
        validatePaperType();
    }
}

public void validatePaperType() {
    paperType = PaperType.getPaperTypeByValue(strPaperType);
    if (paperType == null) {
        errors.put("paperType", "A valid Paper Type is required");
        return;
    }

    if (paperType.equals(PaperType.PRACTICE) && (topicId == null)) {
        errors.put("topicId", "Topic Id is required");
    }
}
于 2012-09-04T23:53:21.800 回答
0

您的idtopicId类变量似乎是整数,但您正试图将它们设置为字符串。

于 2012-09-04T21:31:39.500 回答