`
yuchujin
  • 浏览: 30486 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

tomcat中Jndi的配置

阅读更多
jndi的基本原理不仔细讲了,在sun的教程中有。而且大陆也有翻译过来的文档:
http://yananay.iteye.com/blog/93687

文章是翻译tomcat文档中的jndi resource原文:http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html
Tomcat5 中JNDI Resources配置 ------ 通用JavaBean资源配置(Generic JavaBean Resources)
通常有四个步骤:
1.首先,当然是建一个JavaBean了。  

package com.mycompany;

public class MyBean {

  private String foo = "Default Foo";

  public String getFoo() {
    return (this.foo);
  }

  public void setFoo(String foo) {
    this.foo = foo;
  }

  private int bar = 0;

  public int getBar() {
    return (this.bar);
  }

  public void setBar(int bar) {
    this.bar = bar;
  }


}


2.在web.xml文件中添加如下信息:  

<resource-env-ref>
  <description>
    Object factory for MyBean instances.
  </description>
  <resource-env-ref-name>
    bean/MyBeanFactory
  </resource-env-ref-name>
  <resource-env-ref-type>
    com.mycompany.MyBean
  </resource-env-ref-type>
</resource-env-ref>

3.配置Tomcat的资源工厂:
<Context ...>
  ...
<Resource name="bean/MyBeanFactory" auth="Container"
            type="com.mycompany.MyBean"
            factory="org.apache.naming.factory.BeanFactory"
            bar="23"/>

  ...
</Context>

这段代码可以添加到server.xml中的<host>标签之间,不过,我觉得还是加到每个Tomcat应用所对应的 .xml文件中比较好,易于理解,也不容易出错。

  
4.上述步骤完成之后,就可以在代码中使用配置好的资源了。使用方法示例如下:

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
MyBean bean = (MyBean) envCtx.lookup("bean/MyBeanFactory");

writer.println("foo = " + bean.getFoo() + ", bar = " +
               bean.getBar());


有些需要特别注意的地方如下:
1.)web.xml中添加的元素的顺序不能改变。
2.)在server.xml中添加<context>元素,和在某个web应用对应的 .xml文件中添加<context>元素都可以访问配置好的资源。Tomcat会先检查server.xml,如果两个有相同的配置的话,Tomcat会以server.xml中的为准,并且删除该应用对应的.xml文件,然后产生一个新的。这个新的只包含一个<context>根元素,不包含<resource>元素及其中的其他元素。
3.)资源名称(例子中的是bean/MyBeanFactory,即<Resource>元素中的name属性的值)必须和web.xml中指定的<resource-env-ref-name>的值相同。另外,在资源工厂的参数配置中可以指定JavaBean的属性的初始值。示例代码中就把Bar属性的值设为23了。(JavaBean中Bar的默认值是0).不指定的话,就使用程序中设置的初始值.
原文:
Note that the resource name (here, bean/MyBeanFactory  must match the value specified in the web application deployment descriptor. We are also initializing the value of the bar  property, which will cause setBar(23) to be called before the new bean is returned. Because we are not initializing the foo property (although we could have), the bean will contain whatever default value is set up by its constructor.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics