Alexander Abramovich
Alexander Abramovich

Reputation: 11438

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.

Upvotes: 3

Views: 149

Answers (2)

BertNase
BertNase

Reputation: 2414

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.

Upvotes: 0

skaffman
skaffman

Reputation: 403441

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).

Upvotes: 3

Related Questions