2012-09-04 31 views
1

這裏是我的validate方法 -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"); 
    } 
    } 

的「錯誤」是在操作定義我自己的地圖。我沒有添加任何錯誤到'fieldErrors'。

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

我沒有獲得越來越加入,他們的想法 - 這是怎麼回事,如果我調試「fieldErrors」我看以下兩個條目,即使進入我的「驗證」方法之前。這是我的支持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> 

需要此幫助。由於

回答

2

"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"); 
    } 
} 
+0

如何從堆棧中刪除轉換攔截器或可能修改它。就像發生任何轉換錯誤那樣,那麼不是將其添加到字段錯誤中,而應該將這些值作爲其默認值。這樣我就知道只有一個地方進行驗證。 – Shwetanka

+0

@Shwetanka不是「轉換」攔截器,即「conversionError」攔截器。你修改你的攔截器棧。 –

0

好像你IDtopicId類變量是整數,但你想將它們設置爲字符串。