Jndi is primarily used to configure certain resources in a container so that all projects can be used.
Jndi can provide:
1: Database connection pool.
Custom connection Pooling
Third-party connection pooling
Dbcp
C3p0
Jndi
2: Mail server definition.
3: Load arbitrary classes so that all projects can be used.
jndi:[defined in the Tomcat container, all items must be found in a way that retrieves the service Javax.naming.Context environment (ENV) context.
It's one of the classes: InitialContext
Configure Jndi without publishing the project
1, Configuration Tomcat/conf/server.xml
1 <ContextPath= "/aaa"DocBase= "D:\\adnroid\\workspaces\\day25\\webroot"> 2 <Resourcename= "Jdbc/mysql"Auth= "Container"//name--jndi name Auth--jndi owner3 type= "Javax.sql.DataSource"Driverclassname= "Com.mysql.jdbc.Driver"4 URL= "Jdbc:mysql:///bookstore?characterencoding=utf8"5 username= "root"Password= "MySQL"maxactive= "Ten"Maxidle= "+"6 maxwait= "-1"/>7 </Context>8</Host>
2, put the Mysql-connection.jar in the Tomcat/lib directory
3, in the Java Project reference in the code directly query this jndi:
1 //1. Declaring the context environment2Context ctx=NewInitialContext ();3 //2. Find Apache Environment4ctx= (Context) ctx.lookup ("Java:/comp/env");5 //3. Find Jndi from the environment6Object obj= ctx.lookup ("Jdbc/mysql");7 /*2nd, 3 steps can be synthesized into obj=ctx.lookup ("Java:/comp/env/jdbc/mysql");*/8 //4. Testing9DataSource ds=(DataSource) obj;TenConnection conn=ds.getconnection (); OneSYSTEM.ERR.PRINTLN (conn);
Note:
In general,/server.xml will not be modified,
New "project name. xml" in the directory, insert the code in the 1th step
The standard dbutils
1 Public classDatasourceutils {2 Private StaticDataSource ds;3 Static{4 Try{5Context CTX =NewInitialContext ();6ds = (DataSource) ctx.lookup ("Java:/comp/env/jdbc/mysql");7}Catch(Exception e) {8 e.printstacktrace ();9 }Ten } One Public StaticDataSource Getds () { A returnds; - } -}
Jndi--java Naming and Directory interfaces