Problems for beginners who are directly engaged in Java projects: Role of JNDI in J2EE

Source: Internet
Author: User
Tags websphere application server

It can be understood as follows: JNDI (Java Naming and Directory Interface) is a standard Java Naming System interface provided by Sun, and JNDI provides a unified client API, through the implementation of the jndi spi of different access provider interfaces, the Administrator maps the jndi api to a specific naming service and directory system, this allows Java applications to interact with these naming services and directory services. It is equivalent to a URL that specifies the service location.

 

Http://www.ibm.com/developerworks/cn/java/j-jndi/index.html

It is daunting to master J2EE because the technology and acronyms it contains are constantly growing. Java Naming and Directory Interface (JNDI) has been at the core of Java 2 Platform Enterprise Edition (JEE) since the beginning, but it is often difficult for beginners in J2EE development. This article will eliminate the mystery of the role played by JNDI In the J2EE application and show how it helps the application to free up from deployment details.

Although the J2EE platform has improved the standard of living for ordinary enterprise developers, this improvement is at the cost of having to learn many specifications and technologies, these specifications and technologies are integrated by J2EE to become an all-encompassing distributed computing platform. Dolly developer, a member of many developers, has discovered a feature that helps ease the burden of enterprise-level application deployment. This feature is JNDI, that isJava Naming and Directory Interface). Let's take a look at how Dolly did it without JNDI and how she correctly applied JNDI to improve the situation.

A journey that everyone is very familiar

Dolly developer is writing a web application that uses the JDBC data source. She knows that she is using MySQL, so she encodes a reference to the MySQL JDBC Driver Class and connects to the database in her web application by using the appropriate jdbc url. She realized the importance of the database connection pool, so she included a connection pool package and configured it to use up to 64 connections; she knows that the database server has been set to allow a maximum of 128 clients to connect.

Dolly is heading for disaster

In the development phase, everything went smoothly. However, it is out of control during deployment. Dolly's network administrator told her that she could not access the production server or staging server from her desktop machine, so she had to develop different code versions for each deployment phase. In this case, she needs a new jdbc url, so it also needs to be independently deployed for testing, phase, and production. (Once you hear that you need to establish a separate deployment in each environment, people familiar with configuration management will be defeated, but since this is a very common situation, so they had to stick to their heads .)

When Dolly thinks that establishing independent deployment through different URLs has solved her own configuration problems, she finds that her Database Administrator does not want to run MySQL instances in the production environment. He said that MySQL can also be used for development, but for task-critical data, the Business Standard is DB2. Currently, her build not only varies with the database URL, but also requires different drivers.

Things get worse and worse. Her application is very useful and becomes critical, so that it gets the fault recovery capability from the application server and is replicated to four Server clusters. However, the database administrator protested because every instance of her application uses 64 connections, the database server has only 200 available connections in total-all of which are occupied by Dolly applications. Even more troublesome, DBA has confirmed that Dolly's application only needs 32 connections and is only used for one hour every day. As her applications expand, the application has encountered database-level contention problems. Her only choice is to change the number of connections in the cluster and make preparations, repeat this operation when the number of clusters increases or applications are replicated to another cluster. It seems that she has decided on how to configure the application. The application configuration should be left to the system administrator and database administrator.

 



Back to Top

J2EE role

If Dolly understands the role played by J2EE when developing an application, she may avoid this dilemma. The J2EE specification delegates responsibilities to multiple development roles: component provider, application assembler, deployer, and system administrator ). (In many companies, the roles of component providers and component assemblers are integrated, and the roles of deployers and system administrators are integrated .) Before learning about the JNDI role in J2EE, it is very important to understand the role of J2EE.

Component provider
This role is responsible for creating J2EE components. J2EE components can be Web applications, enterprise-level JavaBean (EJB) components, or application clients (such as swing-based GUI client applications ). Component providers include HTML designers, document programmers, and other developer roles. Most J2EE developers spend a lot of time on the component provider role.

Application Assembler
This role binds multiple J2EE modules into a combined and deployable enterprise archive (EAR) file. The application assembler should select components, distinguish the interaction mode between them, configure their security and transaction attributes, and package the application into the ear file. Many ides, such as WebSphere Studio, idea, JBuilder, WebLogic Workshop, and other ides, can help application assembler to configure the ear file interactively.

Deployer)
This role is responsible for deployment, which means to install the ear to the J2EE container (Application Server), and then configure resources (such as the database connection pool ), bind the resources required by the application to a specific resource on the application server and start the application.

System Administrator)
This role ensures that the resources required by the container can be used by the container.

Role practice

Assume that an enterprise application contains a web application and an EJB component responsible for business logic and persistence. There may be many component vendors developing this application, but in many cases, one person can assume all responsibilities. Components can contain data transmission objects (a jar file), EJB interfaces (another jar file), and EJB implementation itself (another jar file ), and user interface components-servlet, JSP, HTML page and other static Web content. The user interface components are further packaged into web applications, including Servlet classes, JSP files, static content, and jar (including EJB interfaces) of other necessary components ).

It seems that too many components are used, which is almost beyond the imagination of people, especially when considering how many jar files are needed to build a typical web application. However, it is important to realize that dependencies must be managed carefully here. Interfaces and transmission objects are objects that can be depended on by web applications and EJB implementations, but the dependency direction should be the same. Circular dependencies should also be avoided. J2EE components (such as war files and EJB jar files) must declare their resource dependencies outside their deployment units.

The application assembler is responsible for including the dependency content in web applications and packaging them into a single enterprise application. The tool is very helpful here. IDE can help you create a project structure that reflects the module and jar dependencies, and allows you to specify included or excluded modules at will.

The deployer is responsible for ensuring that there are resources required for components in the deployment environment and binding the components to available resources of the platform. For example, an external EJB reference in a web applicationejb-refIs bound to the actual deployed EJB component -- and is bound immediately.

Bind external resources

Any nontrivial J2EE application needs to access information describing the desired environment. This means that when developing and testing components, developers should assume some deployment responsibilities to temporarily test the code. It is important to understand that when you do this, you will be out of the developer's field. Otherwise, you can try to rely on the JDBC driver, URL, JMS queue name, or other machine resources that are unconscious and occasionally potentially catastrophic.

 



Back to Top

JNDI for assistance

Dolly's solution is to clear all direct references to data storage from her application. No reference to the JDBC driver, no server name, no user name or password-or even no database pool or connection management. Dolly needs to write code to ignore the specific external resources to be accessed. It only needs to know that others will provide the links required to use these external resources. This allows the deployer (anyone in this role) to allocate the database connection to the dolly application. Dolly does not need to be involved. (From database security to compliance with the Sarbanes-Oxley Act, she was not involved, and she had enough business reasons to do so .)

Many developers know that the close coupling between code and external resources is a potential problem, but they often forget the division of roles in practice. In small-scale development work (it refers to the team size or deployment scale), it can be successful even if the role division is ignored. (After all, if the application is only a personal application and you are not going to rely on it, it is also good to lock the application on a specific PostgreSQL instance .)

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.

Dolly's situation is worse.

Now let's take a look at Dolly's situation. In her simple web application, she directly uses a JDBC connection from the application code. See list 1. We can see that Dolly explicitly encodes the JDBC driver, Database URL, and her username and password into the servlet:

Listing 1. Typical (but not good) JDBC usage

        Connection conn=null;try {  Class.forName("com.mysql.jdbc.Driver",                true, Thread.currentThread().getContextClassLoader());  conn=DriverManager.getConnection("jdbc:mysql://dbserver?user=dolly&password=dagger");  /* use the connection here */  c.close();} catch(Exception e) {  e.printStackTrace();} finally {  if(conn!=null) {    try {      conn.close();    } catch(SQLException e) {}  }}      

 

If you do not need to specify the configuration information in this way, Dolly (and her peers) uses JNDI to find JDBCDataSourceBetter, as shown in Listing 2:

List 2. Obtain the data source using JNDI

        Connection conn=null;try {  Context ctx=new InitialContext();  Object datasourceRef=ctx.lookup("java:comp/env/jdbc/mydatasource");  DataSource ds=(Datasource)datasourceRef;  Connection c=ds.getConnection();  /* use the connection */  c.close();} catch(Exception e) {  e.printStackTrace();} finally {  if(conn!=null) {    try {      conn.close();    } catch(SQLException e) { }  }}      

 

In order to get the JDBC connection, we must first execute some small deployment configurations so that we can search for them in the local component's JNDIDataSource. This may be cumbersome, but it is easy to learn. Unfortunately, this means that even for the purpose of testing components, developers must be involved in the deployment personnel's territory and be prepared to configure the application server.

Configure JNDI reference

To make the JNDI resolutionjava:comp/env/jdbc/mydatasourceReference, the deployment personnel must<resource-ref>Insert tags into the web. xml file (deployment descriptor of the Web application ).<resource-ref>The label indicates that "This component depends on external resources ". Listing 3 shows an example:

Listing 3. Resource-ref entry

        <resource-ref>  <description>Dollys DataSource</description>  <res-ref-name>jdbc/mydatasource</res-ref-name>  <res-ref-type>javax.sql.DataSource</res-ref-type>  <res-auth>Container</res-auth></resource-ref>      

 

<resource-ref>The entry tells the servlet container that the deployment personnel mustComponent naming context)Setjdbc/mydatasource. Component naming context by prefixjava:comp/env/So the fully qualified local resource name is:java:comp/env/jdbc/mydatasource.

This only defines the local reference to the external resource and does not create the actual resource to which the reference points. (In java, similar situations may be:<resource-ref>Declares a reference, suchObject foo, But nofooSet to actually reference anyObject.)

The deployment personnel's job is to createDataSource(Or createObjectObject, letfooPoint to it, as in our Java language example ). Each container has its own data source setting mechanism. For example, in JBoss, a service is used to define a data source (see $ JBoss/Server/default/deploy/hsqldb-ds.xml and take it as an example), which specifies that you areDataSourceThe global JNDI name of (by defaultDefaultDS). After creating a resource, the third step is still critical: connect the resource or bind it to the local name used by the application component. When a web application is used, the vendor-specific deployment descriptor extension is used to specify the binding. This example is shown in Listing 4. (JBoss is calledjboss-Web.xmlAs a vendor-specific web application deployment descriptor .)

Listing 4. Bind resources to jdi names with vendor-specific deployment descriptors

        <resource-ref>   <res-ref-name>jdbc/mydatasource</res-ref-name>   <jndi-name>java:DefaultDS</jndi-name></resource-ref>      

 

This indicates that the local resource reference name (jdbc/mydatasource) Mapsjava:DefaultDS. If the global resource name changes for some reason and the application code does not need to change, you only need to modify the ing. Here, there are two levels of indirect addressing: a defined and named Resource (java:DefaultDS(jdbc/mydatasource) Bind to the named resource. (In fact, when you map resources at the ear level, there may be Level 3 indirect addressing .)

 



Back to Top

Beyond data sources

Of course, the 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.

Think about this situation: What happens when a company buys a deployable EJB component from order ontology processing services (Oops) to process customer orders. For example, processorders V1.0 is called. Processorders 1.0 has two parts: a group of interfaces and support classes (home and remote interfaces, and transmission classes supported); the actual EJB component itself. Oops is chosen because of its professionalism in this field.

According to J2EE specifications, the company compiled Web applications referenced by ejbs. The company's deployers bound processorders 1.0 to the JNDI tree and used itejb/ProcessOrders/1.0And parse the web application resource name to point to this global JNDI name. So far, these are very common usage of EJB components. However, when we consider the interaction between the company's development cycle and the company's suppliers, things become complicated. Here, JNDI can also help us.

Let's assume that oops has released a new version, processorders V1.1. This new version has some new features that a new application in the company needs, and naturally extends the business interface of the EJB component.

Here, the company has the following options: update all applications to use the new version, write your own version, or use the reference parsing of JNDI, each application is allowed to use its own EJB component version without affecting other applications. Updating all applications immediately is a nightmare for maintenance. It requires a complete regression test for all components, which is usually a daunting task, in addition, if any functional test fails, another round of debugging is required.

Writing internal (in-house) components is often unnecessary. If a component is written by a company with expertise in this business area, it is impossible for a given it store to be as proficient in business functions as a professional component supplier.

As you may have guessed, the best solution is to use JNDI resolution. The JNDI reference of EJB is very similar to the reference of JDBC resources. For each reference, the deployer must specify the name of the new component (for exampleejb/ProcessOrders/1.1) Bound to the global tree. For each other component that requires the EJB component, it must also parse the EJB reference for the component in the deployment descriptor. Applications dependent on versions earlier than V1.0 do not need to be modified or re-tested. This reduces implementation time, costs, and complexity. 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.

 



Back to Top

Conclusion

There is an old computer science joke: Every programming problem can be solved by only one abstract layer (or indirectly. In J2EE, JNDI is the adhesive that combines J2EE applications, but it is not so tight that it is easy to separate and reassemble them. The indirect addressing provided by JNDI allows you to deliver scalable, powerful, and flexible applications across enterprises. This is the commitment of J2EE, and after some planning and pre-consideration, this commitment can be fully implemented. In fact, it is much easier than many people think.

References

  • For more information, see the original article on the developerworks global site.
  • Learn more about JNDI from the JNDI tutorial of Sun Microsystems.
  • "Using JNDI outside J2EE" is taken fromTeach Yourself J2EE in 21 days(SAMS Publishing, January 1, 2004) demonstrates how to define the name service type in use, and how to define the host name and port number of the server on the network.
  • DeveloperworksColumnist Brian Goetz in his article "J2EE or j2se? JNDI works with both "(JavaworldApril 2002), discussed how to use JNDI and j2se for application configuration.
  • Daniel explains the JNDI naming context used in J2EE applications and shows how to "get out of the JNDI Maze ".
  • Using JNDI for WebSphere Application Server J2EE thin client applications shows how to use JNDI in J2EE application clients for communication with remote JNDI providers.
  • InDeveloperworksIn the Java technology area, you can find hundreds of technical articles on various aspects of Java.
  • Visit developer bookstore to obtain a complete list of technical books, including hundreds of books on Java-related topics.

Author Profile

 

Kirk Pepperdine is the chief technology officer of javaperformancetuning.com. He has been focusing on Object Technology and Performance Tuning for the past 15 years. He stillAnt developer's HandbookOne of the authors of MacMillan.

 

 

Joseph ottinger is a consultant in Indianapolis who specializes in J2EE architecture.

Related Article

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.