开发者

Sharing config parameter among servlets

Is there a way two (or more) servlets can share config parameter, declared once in web.xml?

Looked here, but it doesn't seem to be the answer.

The use-case is fairly simple: I have two servlets: one uploads files to a directory, other downloads them. I would be happy to enlist the 开发者_运维百科directory/path only once in web.xml to avoid ambiguity/confusions.


Yes, add a <context-param> to your web.xml, e.g.

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

This is scoped to the webapp as a whole, rather than individual servlets.

You can then obtain this in your servlet(s) from the getInitParameter(...) method of the ServletContext object (which in turn can be obtained using getServletContext() in your servlet).


Or you could declare an <env-entry> in your 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>

The value can then be looked up using JNDI and can be set at deploy time (how this is done is container-specific) without modifying the WAR/EAR file. The <env-entry-value> serves as a default if no deply-time value has been set - it can also be omitted if no meaningful default is available for a particular setting.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜