有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Struts2验证行为怪异

这是我的验证方法-

@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配置文件

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

我需要帮助。谢谢


共 (2) 个答案

  1. # 1 楼答案

    "conversionError" interceptor将接受类型转换错误并将其放入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");
        }
    }
    
  2. # 2 楼答案

    看起来您的idtopicId类变量是整数,但您试图将它们设置为字符串