2011-05-09 92 views
3

有兩種(或多種)servlet可以共享配置參數的方法,在web.xml中聲明一次?在servlets之間共享配置參數

看上去here,但它似乎並不是答案。

用例相當簡單:我有兩個servlet:一個將文件上載到一個目錄,另一個下載它們。我很樂意僅在web.xml中登記目錄/路徑一次,以避免混淆/混淆。

回答

3

是的,請將<context-param>添加到您的web.xml,例如,

<context-param> 
    <param-name>myParam</param-name> 
    <param-value>Some value</param-value> 
</context-param> 

這可以被限制在Web應用程序作爲一個整體,而不是單獨的servlet。

然後,您可以從您的servlet中的getInitParameter(...)方法的ServletContext對象(它可以在您的servlet中使用getServletContext()獲得)獲得。

0

或者你可以在聲明<env-entry>web.xml

<env-entry> 
    <description>This is the address of the SMTP host that shall be used to send mails 
    </description> 
    <env-entry-name>smtp.mailhost</env-entry-name> 
    <env-entry-type>java.lang.String</env-entry-type> 
    <env-entry-value>mailhost</env-entry-value> 
</env-entry> 

使用JNDI值然後可以擡起頭,可以在部署時(這是如何完成的集裝箱專用),而無需修改設置WAR/EAR文件。如果未設置deply-time值,則<env-entry-value>用作默認值 - 如果沒有有意義的默認值可用於特定設置,則也可以省略。