On Sun, 17 Feb 2002, Kennedy Clark wrote:

> Date: Sun, 17 Feb 2002 11:04:09 -0500
> From: Kennedy Clark <[EMAIL PROTECTED]>
> Reply-To: Tomcat Users List <[EMAIL PROTECTED]>
> To: [EMAIL PROTECTED]
> Subject: Access web.xml context-param From A Bean?
>
> I have values I want set at deployment time declared in my web.xml.  I am
> accessing these with no problem from my JSPs with:
>       <%= application.getInitParameter("paramNameHere") %>
>
> However, for my business logic which I have pulled out the if JSPs and put
> into beans, I can't figure out how to access these values?  Is there way to
> get to values stored in the container from a bean?
>

In order to access these parameters, you need a reference to the
ServletContext object for your web application, which is what a JSP page
sees as the "application" variable, inside your JavaBean.  For example,
you might include a setServletContext() method on your bean, and call it
when the bean is created.

An alternative approach that works in Tomcat 4 and any J2EE server is to
use "environment entries" instead of "context initialization parameters"
for this purpose.  For example, the following entry in web.xml:

    <env-entry>
        <env-entry-name>paramNameHere</env-entry-name>
        <env-entry-value>This is the parameter value</env-entry-value>
        <env-entry-type>java.lang.String</env-entry-type>
    </env-entry>

can be accessed from a bean, running inside your web application, like
this:

    import javax.naming.InitialContext;

    public class FooBean {
        ...
        InitialContext context = new InitialContext();
        String paramValue = (String)
          context.lookup("java:comp/env/paramNameHere");
        ...
    }

This works because the container provides an implementation of the
InitialContext APIs (from JNDI) that contains all the environment entries
configured in either the web.xml file or set by appropriate commands in
server.xml.  You don't need a direct reference to the ServletContext to
read them, so no setServletContext() method is required.

Besides environment entries, the JNDI InitialContext can be used to make
lots of other resources available to your web application (such as JDBC
connection pools) but allows them to be configured externally.  For more
information, see the "JNDI Resources How-To" in the Tomcat docs:

    http://localhost:8080/tomcat-docs/jndi-resources-howto.html

or online at:

    http://jakarta.apache.org/tomcat/tomcat-4.0-doc/jndi-resources-howto.html

> TIA, Kennedy
>

Craig


--
To unsubscribe:   <mailto:[EMAIL PROTECTED]>
For additional commands: <mailto:[EMAIL PROTECTED]>
Troubles with the list: <mailto:[EMAIL PROTECTED]>

Reply via email to