简体   繁体   中英

JDBC and JNDI code explanation Jave EE

I am new to Java EE world, in my application I would like to connect to the Database. I was able to accomplish this task with the code below, but can someone explains it to me? What each line does?

code:

try {
    InitialContext initContext = new InitialContext();
    Context env = (Context) initContext.lookup("java:comp/env");
    ds = (DataSource) env.lookup("jdbc/test2");
} catch (NamingException e) {
    throw new ServletException();
}

I also found out that I can use the annotation below in my JSP using tomcat which accomplish the same result as above. Can I use this annotation with any web server, ex GlassFish or Jboos ?

Anotation code:

@Resource(name = "jdbc/test2")
private DataSource ds;

The Java Naming and Directory Interface™ (JNDI) is an application programming interface (API) that provides naming and directory functionality to applications written using the Java™ programming language. 1

The Context object provides the methods for binding names to objects, unbinding names from objects, renaming objects and listing the bindings.

JDNI performs all naming operations relative to a context. Therefore the JDNI defines an InitialContext , which provides a starting point for naming and directory operations. Once you have an initial context, you can use it to look up other contexts and objects.

Many methods in the JDNI package throw a NamingException when they need to indicate that the operation requested cannot be performed. The JDNI has a rich exception hierarchy stemming from the NamingException class. The class names of the exceptions are self-explanatory and are listed here .

You can use the @Resource annotation to inject resources. You can find more information on the correct use here .

Sources:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM