What is JNDI?

Source: Internet
Author: User
Tags ldap ibm developerworks

JNDI is a Java Naming and Directory Interface (Java Naming and Directory Interface). It is one of the important specifications in the J2EE specification. Many experts believe that they do not fully understand the significance and role of JNDI, no real knowledge of J2EE, especially EJB.
So what is the role of JNDI?

To understand the role of JNDI, we can refer to "What should we do without JNDI? After using JNDI, what will we do ?" This issue is discussed.

Without JNDI:
When developing, programmers know that they want to develop applications that access the MySQL database. Therefore, they encode a reference to the MySQL JDBC Driver Class and connect to the database by using the appropriate jdbc url.
Like the following code:

Java code
Connection conn=null;try {  Class.forName("com.mysql.jdbc.Driver",                true, Thread.currentThread().getContextClassLoader());  conn=DriverManager.getConnection("jdbc:mysql://MyDBServer?user=qingfeng&password=mingyue");    ......  conn.close();} catch(Exception e) {  e.printStackTrace();} finally {  if(conn!=null) {    try {      conn.close();    } catch(SQLException e) {}  }}

This is a traditional practice and is also a common practice for non-Java programmers (such as Delphi and VB. In general, this method will not cause problems in small-scale development. As long as programmers are familiar with the Java language, understand the JDBC technology and MySQL, they can quickly develop corresponding applications.

Problems with the absence of JNDI:
1. The database server name mydbserver, user name, and password may need to be changed, resulting in the jdbc url needing to be modified;
2. The database may use another product. For example, if you use DB2 or Oracle, The JDBC driver package and class name must be modified;
3. As the number of terminals in use increases, the original connection pool parameters may need to be adjusted;
4 ,......

Solution:
Programmers do not need to worry about "what is the specific database background? What is the JDBC driver? What is the jdbc url format? What is the user name and password used to access the database ?" And so on, the program compiled by the programmer should not reference the JDBC driver, no server name, no user name or password-or even no database pool or connection management. Instead, the problem is assigned to the J2EE container for configuration and management. The programmer only needs to reference the configuration and management.

As a result, JNDI is available.

After using JNDI:
First, configure the JNDI parameter in the J2EE container, define a data source, that is, the JDBC reference parameter, and set a name for the data source. Then, in the program, use the data source name to reference the data source to access the background database.
The procedure is as follows (using JBoss as an example ):
1. Configure the data source
Under the D:/jboss420ga/docs/examples/JCA folder of JBoss, there are many data source definition templates referenced by different databases. Copy the mysql-ds.xml file to the server you are using, such as D:/jboss420ga/Server/default/deploy.
Modify the contents of the mysql-ds.xml file so that you can access your MySQL database correctly through JDBC, as shown below:
<? XML version = "1.0" encoding = "UTF-8"?>
<Datasources>
<Local-TX-datasource>
<JNDI-Name> mysqlds </JNDI-Name>
<Connection-URL> JDBC: mysql: // localhost: 3306/LW </connection-URL>
<Driver-class> com. MySQL. JDBC. Driver </driver-class>
<User-Name> root </user-Name>
<Password> rootpassword </password>
<Exception-sorter-class-Name> org. JBoss. Resource. Adapter. JDBC. Vendor. mysqlexceptionsorter </exception-sorter-class-Name>
<Metadata>
<Type-mapping> mysql </type-mapping>
</Metadata>
</Local-TX-datasource>
</Datasources>

Here, a data source named mysqlds is defined. Its parameters include jdbc url, Driver Class Name, user name, and password.

2. reference the data source in the program:

Java code
Connection conn = NULL; try {context CTX = new initialcontext (); object datasourceref = CTX. lookup ("Java: mysqlds"); // reference the data source datasource DS = (datasource) datasourceref; Conn = Ds. getconnection ();...... c. close ();} catch (exception e) {e. printstacktrace ();} finally {If (Conn! = NULL) {try {conn. Close () ;}catch (sqlexception e ){}}}

The amount of programming code for directly using JDBC or referencing a data source through JNDI is almost the same, but the current program does not need to care about specific JDBC parameters.
After the system deployment, if the database parameters change, you only need to reconfigure the mysql-ds.xml to modify the JDBC parameters, as long as the data source name remains unchanged, then the program source code does not need to be modified.

It can be seen that JNDI avoids the tight coupling between the program and the database, making the application easier to configure and deploy.

JNDI extension:
In addition to meeting the data source Configuration Requirements, JNDI further expands its role: All references to resources outside the system can be defined and referenced through JNDI.

Therefore, in J2EE specifications, resources in J2EE are not limited to JDBC data sources. There are many types of references, including resource references (discussed), Environment entities, and EJB references. In particular, EJB references expose another key role of JNDI in J2EE: Find other application components.

The JNDI reference of EJB is very similar to the reference of JDBC resources. In an environment where services tend to be converted, this is a very effective method. This type of configuration management can be performed on all components in the application architecture, from EJB components to JMS queues and topics, to simple configuration strings or other objects, this can reduce the maintenance costs incurred by service changes over time, simplify deployment, and reduce integration work. External resources ".

Summary:
The J2EE specification requires that all J2EE containers provide the implementation of the jndi specification. The role of JNDI in J2EE is "Switch"-a general mechanism for J2EE components to find other components, resources, or services at runtime. In most cases, the container that provides the JNDI supplier can act as a limited data storage, so that the administrator can set the execution attribute of the application, and let other applications reference these attributes (Java Management Extensions (JMX) can also be used for this purpose ). The primary role of JNDI in J2EE applications is to provide an indirect layer, so that components can discover the required resources without understanding these indirect properties.

In J2EE, JNDI is the binder that combines J2EE applications. The indirect addressing provided by JNDI allows cross-enterprise delivery of scalable, powerful, and flexible applications. This is the commitment of J2EE, and after some planning and pre-consideration, this commitment can be fully implemented.

 

To put it bluntly, you need to name the resource and then find the resource based on the name.

// ================================================ ========================================================== ======================================

First, let's review the simple question, which is listed in the first point below.
1. We know that Java starts running from static main. Why should we start from the static method?
2. How can I find an object that exists in another part of the world and the server is ready for us before we start working? If this object is created by my class, it is of course simple. You can call it directly by referencing the object. If this object is not created by me, I want to actively call its method, which seems impossible in any programming language. Remember to write a method that is called by others rather than actively calling others.

Just as if you are looking for someone, if he hasn't established a contact with you (the connection is to save an object reference, if two objects have not created another object, and they have not been established by any third party, the problem arises.) How do you deal with them?
In reality:
A. We dial 114.
In Java: context CTX = new initialcontext ();
B. Where can I find a restroom? 114 answer, xxx... transfer for you. Please wait.
In Java: datasource DS = (datasource) CTX. Lookup ("convenience service company ");
C. After a while, people will come. You said: Teacher Fu, please help me with the toilet.
In Java: Ds. getconnection ();

In the above words, I did not answer you what is JNDI, But I answered why we need JNDI. I hope you can understand the concept of it.

Here, we will give you some guidance on how to better understand the implementation of JNDI:
1. if an object is in another place (possibly not in the same VM/process as the currently running program), how can an object be sent from one VM to another? What should I do if the object state needs to be permanently saved (after the server process is restarted) like LDAP? Take a look at the JNDI statefactory. It converts an object into a certain way to save it, just as when we save an entity object, we will use SQL for it.

2. There is an object that has been saved last time, and now the server has restarted. The last object is definitely not in the memory. How can we restore the last state?
Please refer to the JNDI objectfactory. It reads some status information that was last saved to create and initialize an object. For example, we have configured an XML file, which is the configuration data of a JDBC data source. The application server reads this information (equivalent to the previous state) at startup and then restarts the object.

3. How can I configure a new implementation class in a simple way when enterprise applications are so complex and interface-oriented? Java practices:
The SPI (Service Provider Interface) has been defined, including the following:
The interface is ready, for example, statefactory/objectfactory.
Configuration: first search for a jndiprovider under the JRE. the properties file is used as the default implementation, and then find the/JNDI under the root path of the user classpath. properties. in addition, system. getproperties () and create initialcontext to give a hashtable as the parameter. These three parameters have a priority relationship. The more specific parameters are followed, the higher the priority, the greater the front, the lower the general-purpose parameter priority. For this, see the source code of the JDK ResourceManager class.
How are implementation classes and initialization completed automatically? You need to check the constant in the context interface and the sample parameter value of the constant in the context interface in the example of the Sun LDAP initialcontextfactory running. Generally, it is very important that the parameter initialcontextfactory is used, but sometimes there are other parameters to be configured, such as pkgs. It means that we give a package name, And the JNDI Manager uses this package name list as the package name when looking for the implementation, the class name is the protocol name + fixed Suffix: for example: LDAP: // localhost: 389, it uses a 'package name prefix. protocol name. protocol name
+ Urlcontextfactory 'is used as the class name to search for a class. If it exists, it is regarded as the implementation class. If it is not found, try another package name prefix. You can check COM. sun. JNDI. the URL name. For example, LDAP: // is used to find a class COM. sun. JNDI. URL. LDAP. ldapurlcontextfactory, if it is DNS: // www.163.com/xxx, find a COM. sun. JNDI. URL. DNS. dnsurlcontextfactory. This is the URL context Factory
That is, when you use CTX. Lookup ("Java: xxxx/yyy") with a protocol prefix.

In addition, you can also look at com. sun. www. the class in the Protocol package, which is not a URL stream handler processing rule unrelated to JNDI, is almost identical with some designs and configurations. I have previously written a JDBC: oracle: username/password: @ localhost: 1521: Training/[select a from C where del_ind = 0], input this URL in the Java program. We can read the data in the database, and you can enter file:/C:/boot. ini
After reading the content of this file, I wrote a URL stream handler that supports the JDBC protocol and configured it in the command line. Other Application classes can be automatically processed, they do not know the data I read from the database.

4. Starting from J2EE 1.3, resource management is managed and configured by the Application Server separately. This is different from J2EE 1.2. in J2EE 1.2, we directly configure the resources we need in the application. In J2EE 1.3, we configure a data source on the server. In the application, we only need to describe the reference of the resource we configured. For example, we only need. XML or ejb-jar.xml configuration <resource-ref/> instead of the data source itself. What are the benefits? For example, we have defined two training data sources: JDBC/training/db2. JDBC/Oracle/db2.
One is the development environment and the other is the UAT environment. Now, when we build a <resource-ref/> pointing to JDBC/training/DB2, we will use the DB2 database, during the UAT test, if we set up another <resource-ref/> pointing to JDBC/training/Oracle, the Oracle database will be used. This does not need to modify the code, but only modifies the web. XML/ejb-jar.xml, and now the user name and password to connect to the data is no longer a matter of application development itself, because you do not need to configure resources and do not need to know its login name and password, the administrator configures the data source on the server. Note that the developer is responsible for configuring the resource source.
The roles of component provider and deployer are separated. Although deployer is delegated to developers in reality, the J2EE specifications are described separately.

5. What is the purpose of the above half-day discussion? This is my first painful experience. I wrote EJB and bought a book. I learned from getting started with J2EE (that is, the legendary series ), write a stateless Session Bean to access the data source. The data source cannot be found: namingexception: XXX not found. I saw an article on IBM developerworks, which was originally about J2EE 1.2. The default configuration of wsad 5.1.2 for development is J2EE 1.3. This introduces the JNDI linkref. to configure a resource on the server mentioned in the above 4, but configure a reference in the application, currently, the application server basically uses the JNDI technology implementation.
Linkref. This is a class in JNDI. When the server is started, a JDBC/training/DB2 and JDBC/training/Oracle datasource object (objectfactory is used) will be created. When an application accesses the data source to be accessed, the server detects the web. with <resource-ref/> specified in the XML/ejb-jar.xml, it creates a linkref and puts it in the Context. Its name is JDBC/training, however, its ref is JDBC/training/db2.
In this case, we use CTX. during Lookup ("Java: JDBC/Training"), the javaurlcontextfactory corresponding to the Java protocol will find this JDBC/training object. When detecting that it is a linkref object, it will automatically use its ref value (JDBC/training/DB2 here) and then lookup again. Now we finally find the data source object JDBC/training/DB2.

6. There are other related items in JNDI. Link ref inherits from a reference concept. To learn more about a specific implementation details, please take a copy of Apache commons-xxx.jar (name I forgot, however, people who have used spring/hibernate to create data sources may know that they use xxxdatasource for a method that does not need to be configured on the server, but can use data source ), I do not recommend this jar. I recommend that you read the xxxdatasource source code, which demonstrates the usage of an objectfactory. This and
The configuration and use of other J2EE managed resources such as JMS connectionfactory are implemented using the same technology. The opposite is true.
For more information, see the implementation of statefactory and reference source code. As a medium-level J2EE programming, you should at least understand the configuration of objectfactory/linkref/SPI/resource ref in terms of concept and theory, it would be better if you know how statefactory is implemented.

7. The remaining source code for self-taught open-source projects. Although it takes more time, we can draw a line from each other without having to repeat Google flood stickers.

JNDI is a Java Naming and Directory Interface (Java Naming and Directory Interface). It is one of the important specifications in the J2EE specification. Many experts believe that they do not fully understand the significance and role of JNDI, no real knowledge of J2EE, especially EJB.
So what is the role of JNDI?

To understand the role of JNDI, we can refer to "What should we do without JNDI? After using JNDI, what will we do ?" This issue is discussed.

Without JNDI:
When developing, programmers know that they want to develop applications that access the MySQL database. Therefore, they encode a reference to the MySQL JDBC Driver Class and connect to the database by using the appropriate jdbc url.
Like the following code:

Java code
Connection conn=null;try {  Class.forName("com.mysql.jdbc.Driver",                true, Thread.currentThread().getContextClassLoader());  conn=DriverManager.getConnection("jdbc:mysql://MyDBServer?user=qingfeng&password=mingyue");    ......  conn.close();} catch(Exception e) {  e.printStackTrace();} finally {  if(conn!=null) {    try {      conn.close();    } catch(SQLException e) {}  }}

This is a traditional practice and is also a common practice for non-Java programmers (such as Delphi and VB. In general, this method will not cause problems in small-scale development. As long as programmers are familiar with the Java language, understand the JDBC technology and MySQL, they can quickly develop corresponding applications.

Problems with the absence of JNDI:
1. The database server name mydbserver, user name, and password may need to be changed, resulting in the jdbc url needing to be modified;
2. The database may use another product. For example, if you use DB2 or Oracle, The JDBC driver package and class name must be modified;
3. As the number of terminals in use increases, the original connection pool parameters may need to be adjusted;
4 ,......

Solution:
Programmers do not need to worry about "what is the specific database background? What is the JDBC driver? What is the jdbc url format? What is the user name and password used to access the database ?" And so on, the program compiled by the programmer should not reference the JDBC driver, no server name, no user name or password-or even no database pool or connection management. Instead, the problem is assigned to the J2EE container for configuration and management. The programmer only needs to reference the configuration and management.

As a result, JNDI is available.

After using JNDI:
First, configure the JNDI parameter in the J2EE container, define a data source, that is, the JDBC reference parameter, and set a name for the data source. Then, in the program, use the data source name to reference the data source to access the background database.
The procedure is as follows (using JBoss as an example ):
1. Configure the data source
Under the D:/jboss420ga/docs/examples/JCA folder of JBoss, there are many data source definition templates referenced by different databases. Copy the mysql-ds.xml file to the server you are using, such as D:/jboss420ga/Server/default/deploy.
Modify the contents of the mysql-ds.xml file so that you can access your MySQL database correctly through JDBC, as shown below:
<? XML version = "1.0" encoding = "UTF-8"?>
<Datasources>
<Local-TX-datasource>
<JNDI-Name> mysqlds </JNDI-Name>
<Connection-URL> JDBC: mysql: // localhost: 3306/LW </connection-URL>
<Driver-class> com. MySQL. JDBC. Driver </driver-class>
<User-Name> root </user-Name>
<Password> rootpassword </password>
<Exception-sorter-class-Name> org. JBoss. Resource. Adapter. JDBC. Vendor. mysqlexceptionsorter </exception-sorter-class-Name>
<Metadata>
<Type-mapping> mysql </type-mapping>
</Metadata>
</Local-TX-datasource>
</Datasources>

Here, a data source named mysqlds is defined. Its parameters include jdbc url, Driver Class Name, user name, and password.

2. reference the data source in the program:

Java code
Connection conn = NULL; try {context CTX = new initialcontext (); object datasourceref = CTX. lookup ("Java: mysqlds"); // reference the data source datasource DS = (datasource) datasourceref; Conn = Ds. getconnection ();...... c. close ();} catch (exception e) {e. printstacktrace ();} finally {If (Conn! = NULL) {try {conn. Close () ;}catch (sqlexception e ){}}}

The amount of programming code for directly using JDBC or referencing a data source through JNDI is almost the same, but the current program does not need to care about specific JDBC parameters.
After the system deployment, if the database parameters change, you only need to reconfigure the mysql-ds.xml to modify the JDBC parameters, as long as the data source name remains unchanged, then the program source code does not need to be modified.

It can be seen that JNDI avoids the tight coupling between the program and the database, making the application easier to configure and deploy.

JNDI extension:
In addition to meeting the data source Configuration Requirements, JNDI further expands its role: All references to resources outside the system can be defined and referenced through JNDI.

Therefore, in J2EE specifications, resources in J2EE are not limited to JDBC data sources. There are many types of references, including resource references (discussed), Environment entities, and EJB references. In particular, EJB references expose another key role of JNDI in J2EE: Find other application components.

The JNDI reference of EJB is very similar to the reference of JDBC resources. In an environment where services tend to be converted, this is a very effective method. This type of configuration management can be performed on all components in the application architecture, from EJB components to JMS queues and topics, to simple configuration strings or other objects, this can reduce the maintenance costs incurred by service changes over time, simplify deployment, and reduce integration work. External resources ".

Summary:
The J2EE specification requires that all J2EE containers provide the implementation of the jndi specification. The role of JNDI in J2EE is "Switch"-a general mechanism for J2EE components to find other components, resources, or services at runtime. In most cases, the container that provides the JNDI supplier can act as a limited data storage, so that the administrator can set the execution attribute of the application, and let other applications reference these attributes (Java Management Extensions (JMX) can also be used for this purpose ). The primary role of JNDI in J2EE applications is to provide an indirect layer, so that components can discover the required resources without understanding these indirect properties.

In J2EE, JNDI is the binder that combines J2EE applications. The indirect addressing provided by JNDI allows cross-enterprise delivery of scalable, powerful, and flexible applications. This is the commitment of J2EE, and after some planning and pre-consideration, this commitment can be fully implemented.

 

To put it bluntly, you need to name the resource and then find the resource based on the name.

// ================================================ ========================================================== ======================================

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.