W
W
wolf-98302016-09-21 20:11:20
Java
wolf-9830, 2016-09-21 20:11:20

How to connect to db in java web?

I use apache tomcat, following the documentation I created a resource in the context file in the / conf of the server, described the connection there, in fact everything is clear, it became not clear from this part of the documentation:

Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/myoracle");
Connection conn = ds.getConnection();

1. What is InitialContext();?
2. What is this mysterious lookup method and its parameter?
3. How is a connection to the database established in real and large java applications? What in each servlet (well, or controller) to write those three lines above?
Author: former php programmer

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Cheremisin, 2016-09-21
@wolf-9830

I hope you are using a connection pool. Otherwise, you will have an uncontrolled number of connections to the database and everything will fail and slow down at some stage, especially with oracle.
Now for the questions:
1) InitialContext - initialization of the context for searching for resources in the global registry. It's kind of like LDAP inside J2EE application servers. This is only needed to find already initialized resources that are ready to go. A simple analog in the real world is Microsoft AD, or the directory service, or the Windows registry.
2) Actually the search for a resource by its name. A ready initialized resource is returned. In your case, the application context is requested first (second line), and then the connection to the database is requested in it.
3) Yes, this is the correct method. Once again, I note that the connection to the database itself does not take place here, a ready-made initialized connection to the database is requested here. Everything happens very quickly. Well, with this method, you can request not only a connection to the database, but also a whole bunch of resources that the application server provides, such as queues, jmx bins, all kinds of connectors, distributed services, and other zombie enterprises.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question