2012-01-17 91 views
0

我編寫了自定義標記,可以很容易地本地化字符串;自定義標記從servlet中獲取空值並捕獲異常

在jsp中它看起來像這樣:

<ct:word key="${message}"/> 

消息從Servlet進行傳遞。 該標籤從ResourceBundle中獲取所需的字符串。 一切正常,但存在問題。如果我沒有從servlet傳遞消息,那麼我的應用程序拋出異常(ResourceBundle找不到必要的字符串)。
如何確保自定義標籤不響應空值並跳過?像它

<c:out /> 

代碼即時通訊我的自定義標籤:

private String key; 
private String value; 

public void setKey(String key) { 
    this.key = key; 
} 

public String getKey() { 
    return this.key; 
} 

public int doStartTag() { 
    try { 
     this.checkLocale();//check locale and init resourceBundle 
     value = resourceBundle.getString(key); 
     pageContext.getOut().write(value); 
    } catch (IOException e) { 
     logger.error(e); 
    } catch (MyException e1) { 
     logger.error(e1); 
    } 
    return SKIP_BODY; 
} 

我不想使用

<c:if test="${not empty message}"/> or <c:when/> 

它的雜波

修訂在JSP代碼: 我試試

} catch (MyException e1) { 
     logger.error(e1); 
     return SKIP_BODY; 
    } 

,但我有例外:

java.util.MissingResourceException: Can't find resource for bundle java.util.PropertyResourceBundle, key 
在我的方法

我趕上

catch (MissingResourceException e) { 
     throw new MyException(Constants.ERROR_TRANSLATE_TAG,e); 
    } 

我的應用程序問題,此異常只有當我沒從servlet的將此消息傳遞。我想要顯示頁面,即使我沒有這個消息,沒有錯誤頁面。

+0

您是否嘗試捕獲'MissingResourceException'? – Thomas 2012-01-17 21:06:11

+0

是的,爲了避免拉出所有異常,我在try/catch塊中拋出MyException。雖然我不知道如何處理這個異常,但我只是寫下這個錯誤。 – Ifozest 2012-01-17 21:10:38

+0

既然你返回'SKIP_BODY'並且不應該進入'pageContext.getOut()。write(value);'當拋出一個'MissinResourceException'的行時,一切都應該沒問題。或者當應該由servlet設置密鑰時,你會得到一個異常嗎?在這種情況下,你能告訴我們你的標籤描述嗎? – Thomas 2012-01-17 21:41:12

回答

0

爲了記錄在案:

resourceBundle.getString(key);將拋出MissingResourceException如果密鑰無法找到,從而捕獲了異常,以及在doStartTag()方法。