2013-05-12 66 views
0

我正在爲我的應用程序使用Struts 1.2。我有我的表單驗證方法,我正在做一些驗證用戶提供的輸入。下面是由用戶提供的userName的代碼:如果用戶名是不是由用戶wntered,然後應顯示在UI上述錯誤消息未在UI中顯示Struts錯誤消息

@Override 
public ActionErrors validate(ActionMapping mapping, 
     HttpServletRequest request) { 

    System.out.println("Validating the Form..."); 
    ActionErrors errors = new ActionErrors(); 

    if(userName != null && userName.length() <= 0) 
     errors.add("userName",new ActionError("Invalid UserName")); 

    return errors; 
} 

。以下是我在jsp文件中用於顯示以上錯誤消息的代碼:

<logic:messagesPresent property="userName">        
    <html:messages id="userName" property="userName"> 
     <bean:write name="userName"/> 
    </html:messages> 
</logic:messagesPresent> 

但它沒有顯示任何錯誤消息。

我也試過這種替代,但這也沒有工作:

<logic:messagesPresent property="userName">        
     <html:errors property="userName" /><html:errors/>  
</logic:messagesPresent> 

當我嘗試調試代碼,是越來越在form執行validate方法和execute方法不會被觸發,因爲有驗證錯誤。在用戶界面中,不會顯示錯誤消息。請讓我知道如何解決這個問題。

回答

2

ActionError本身不帶錯誤信息。相反,它會在application's MessageResources bundle中輸入錯誤消息的關鍵字。

從Struts的文檔上Automatic Form Validation

返回含有ActionMessage的的,它們是包含應該顯示的錯誤消息密鑰(在應用程序的的MessageResources束)類的的ActionErrors實例。

所以,你應該做這樣的事情:

errors.add("userName",new ActionError("userName.invalid")); 

然後,在你的資源包,你應該有這樣的事情:

userName.invalid=Invalid UserName 

而且,Struts的1 .x已經很老了,已經達到了End-Of-Life。如果這是一個新的應用程序,我會建議尋找更新的東西。

+0

謝謝,它解決了我的問題。 – user182944 2013-05-12 11:55:44