JNDI
一直对jndi(Java Naming and Directory Interface,JNDI)认识很肤浅,虽然项目有用到,但是我总觉得和jdbc一样。等有时间去慢慢研究把
两种方式:
$CATALINA_BASE/conf/web.xml : 你可以暴露资源给所有的web应用,每个web应用在context中使用resourcelink来进行引入(不过还是建议在/WEB-INF/web.xml中直接配置WEB应用程序的资源需求)
the per-web-application context XML file
/WEB-INF/web.xml
1.通用的javabean资源
(1)定义一个javabean
public class MyBean {
private String foo = "Default Foo";
private int bar = 0;
public String getFoo() {
return (this.foo);
}
public void setFoo(String foo) {
this.foo = foo;
}
public int getBar() {
return (this.bar);
}
public void setBar(int bar) {
this.bar = bar;
}
}
(2)在/WEB-INF/web.xml中添加
<resource-env-ref>
<description>Object Factory for MyBean instance</description>
<resource-env-ref-name>
bean/MyBeanFactory
</resource-env-ref-name>
<resource-env-ref-type>
com.javabean.MyBean
</resource-env-ref-type>
</resource-env-ref>
(3)在/META-INF/中新建context.xml然后添加
<Resource name="bean/MyBeanFactory" auth="Container"
type="com.javabean.MyBean"
factory="org.apache.naming.factory.BeanFactory"
bar="23"/>
完成上述步骤后,写测试类
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");//All configured entries and resources are placed in the java:comp/env portion of the JNDI namespac
MyBean bean = (MyBean)envCtx.lookup("bean/MyBeanFactory");
System.out.println(bean.getBar()+" : "+bean.getFoo());
2.UserDatabase Resources
这个资源涉及到tomcat的用户管理。与tomcat安全有关系,我也只是大致了解下,没有深入研究,毕竟谁会把不信任的项目放入自己的tomcat中。
(注意:这个可能与安全有关系realm)
3.javamail sessions
这块完全不了解,也没使用过。放过把。
4.JDBC Data Source
(1)install jdbc driver。这个jar包tomcat容器和web应用都要能访问,那最好是放到$CATALINA_HOME/lib下
(2)Declare your resource requirements
修改/WEB-INF/web.xml
<resource-ref>
<description>
jndi
</description>
<res-ref-name>
jdbc/EmployeeDB
</res-ref-name>
<res-type>
javax.sql.DataSource
</res-type>
<res-auth>
Container
</res-auth>
</resource-ref>
(3)Configure tomcat's Resource Factory修改META-INF/context.xml
<Resource name="jdbc/EmployeeDB" auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
username="test"
password="test"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:orac"/>
基本上就可以了,跑的时候出现
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1150)
纠结了好长时间,后来才发现,我是用tomcat6发布的,但是我看的文档是tomcat7。我把发布包拷贝到tomcat7下,然后修改$CATALINA_HOME的路径,然后就能顺利的跑起来。后来我又下了tomcat6的源代码反正这个报错的类我是没找到,可能下的版本不一样。
如果上述的资源factory不能满足要求,你可以自定义一个资源factory
浙公网安备 33010602011771号