---
title: "jndi study"
author: "lujin55"
date: "2012-05-23T23:41:01Z"
tags: []
categories: ["编程语言"]
slug: "jndi-study"
draft: false
lastmod: "2012-06-03T14:03:12Z"
id: 1492536
url: "https://lujin55.iteye.com/blog/1492536"
---

jndi  jave naming and directory interface java命名和目录接口。主要用于远程访问对象（标准）。

naming service: the means by which names are associated with objects and objects are found based their name, 命名服务，通过名字与对象的联系，我们可以根据名字找到相应的对象
directory service: a directory service associated names with the objects and also allow such objects to have attributes.目录服务，可以说是命名服务的扩展，它不仅联系了对象，并且允许对象拥有属性

java应用程序使用jndi api访问不通的命名和目录服务，jndi提供了访问不同jndi服务标准统一的接口。

几个命名/目录服务的提供者
1 LDAP   lightweight directory access protocol     com.sun.jndi.ldap.LdapCtxFactory
2 CORBA COS  Common Object request broker architecture Common object services
3 RMI    java remote method invocation
4 DNS    Domain name system
com.sun.jndi.dns.DnsContextFactory
5 FSSP   file system service provider              com.sun.jndi.fscontext.RefFSContextFactory

图片中更加可以明白jndi的作用
![](http://dl.iteye.com/upload/attachment/0068/5576/d5a5e94f-5981-38d4-909d-f6560fffbc75.jpg)
java spi   server provider interface


Naming operations：
read operations and operations for updating the namespace
Look up an object
List the content of a context
Addind,overwriting,and removing a binding
Renaming an object
Creating and destorying subContexts

Directory operations
Reading a object's attributes
Modifying an object's attributes
Searching a directory
Performing hybrid naming and directory operations

代码，Lookup，通过名字找到找到对象，正如new File("H:/summary.txt");提供名字可以获取File对象。

```java

package ldaptest;

import java.io.File;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author liuquan
 */
public class LdapLookup {
    
    public void lookupObject(){
        Hashtable ht = new Hashtable();
        ht.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
        ht.put(Context.PROVIDER_URL, "file:/H:");
        try {
            Context context = new InitialContext(ht);
            File file = (File)context.lookup("summary.txt");
            System.out.println(file.getAbsolutePath());
        } catch (NamingException ex) {
            Logger.getLogger(LdapLookup.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        LdapLookup lookup = new LdapLookup();
        lookup.lookupObject();
    }
}

```

使用的是file system service。Hashtable存放了二个参数，一个是service的提供者，另一个是访问路径。

代码list the content of the context，得到context内所有内容。如你访问文件夹，那么可以得到这个文件夹里面所有的内容。有二个方法，一个只得到object名字和class名字，另一种还会得到object对象。

```java

package ldaptest;

import java.io.File;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;

/**
 *
 * @author liuquan
 */
public class LdapList {

    public void listObject() {
        try {
            Hashtable ht = new Hashtable();
            ht.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
            ht.put(Context.PROVIDER_URL, "file:/H:");
            Context context = new InitialContext(ht);
            NamingEnumeration list = context.list("summary");
            while (list.hasMore()) {
                NameClassPair ncp = (NameClassPair) list.next();
                System.out.println(ncp);
                System.out.println(ncp.getName());
                System.out.println(ncp.getClassName());

            }
        } catch (NamingException ex) {
            Logger.getLogger(LdapList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void listBindingObject() {
        try {
            Hashtable ht = new Hashtable();
            ht.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
            ht.put(Context.PROVIDER_URL, "file:/H:");
            Context context = new InitialContext(ht);
            NamingEnumeration list = context.listBindings("summary");
            while (list.hasMore()) {
                Binding b = (Binding) list.next();
                System.out.println(b);
                System.out.println(b.getObject());
                File file = (File) b.getObject();
                System.out.println(file.getAbsolutePath());
            }
        } catch (NamingException ex) {
            Logger.getLogger(LdapList.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String args[]) {
        LdapList ll = new LdapList();
        ll.listObject();
        ll.listBindingObject();
    }
}

```