`

JNDI--只是一种获取文件的另一种方式

    博客分类:
  • JNDI
阅读更多
jndi 简单的说就是 把一种功能服务,用另一种方式表现出来,这种方式就是jndi。

举个例子。

我想要获取 磁盘上的 一个文件,假如说是“C:/aaa.txt”

正常的情况下我就要

File file =new File("C:/aaa.txt");

这样我就得到了文件对象,然后对干对象进行操作。

然而还可以使用 jndi来实现这种功能,

Hashtable env = new Hashtable();

env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");


Context ctx = new InitialContext(env);

(以上3句可以这样写,其实这个部分就是启动jndi服务)

System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");

Context ctx = new InitialContext();

---------------------------------------------------------------------------------------------------------------------------------------

接下来

Object obj = ctx.lookup(“C:/aaa.txt”);

File file = (File)obj;

这样也获取了这个文件对像。



jndi配置数据源:
在applicationContext.xml(spring配置文件)文件中:
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/wydb" />

在web.xml文件中:

   <resource-ref >
  <description></description>
  <res-ref-name>jdbc/wydb</res-ref-name>
  <res-type>javax.sql.DataSource</res-type>
  <res-auth>Container</res-auth>
  <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

在(tomcat)sever.xml中:

<Context docBase="eWeb" path="/neweb" reloadable="true" source="org.eclipse.jst.j2ee.server:eWeb">
<Resource name="jdbc/wydb" auth="Container" type="javax.sql.DataSource" username="EUSER" password="EUSER" driverClassName="oracle.jdbc.driver.OracleDriver"
      url="jdbc:oracle:thin:@192.168.1.130:1521:devdb" maxActive="8" maxIdle="4"      factory="org.apache.commons.dbcp.BasicDataSourceFactory" />
</Context>

个人总结

优点:例如在websphere(类似tomcat)加上数据库连接的配置就更安全
缺点:在开发时不易用此配置方法,在用cvs将程序下载到本地时任然需要配置,繁琐了些;但是在发布的时候可以用。










在java中也可以通过它来获取想要的资源:

public DBConnection() {
        try {
            Context ctx = new InitialContext();
     if (ctx == null) throw new Exception("No Context");
     DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/oracle");
            if (ds == null) throw new Exception("jdbc/oracle is an unknown DataSource");
            conn = ds.getConnection();
            stmt = conn.createStatement();
        } catch (Exception e) {
            System.out.println("naming:" + e.getMessage());
        }
    }


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics