three ways to configure Tomcat under Jndi
Jndi (Java naming and directory Interface,java naming and directory interfaces) is a set of APIs that access naming and directory services in Java applications. The naming service links names to objects so that we can use names
Access the object. A directory service is a naming service in which objects are not only named but also attributes.
Tomcat configuration Jndi has global configuration and local configuration. There are roughly three ways to configure this:
The first type: global configuration.
1) in the Context.xml configuration file under Tomcat's Conf folder, add:
<resource name= "Jndi/mybatis" auth= "Container" type= "Javax.sql.DataSource" Driverclassname= " Com.mysql.jdbc.Driver "url=" jdbc:mysql://localhost:3306/appdb "username=" root "password=" 123456 "maxactive=" 20 " maxidle= "maxwait=" 10000 "/>
2) Add a resource reference to the project's Web. XML:
<resource-ref> <description>jndi datasource</description> <res-ref-name>jndi/mybatis</ Res-ref-name> <res-ref-type>javax.sql.DataSource</res-ref-type> <res-auth>container</ Res-auth></resource-ref>
Where the Res-ref-name value is the same as the name value of Context.xml.
3) Jndi test method:
public void Testjndi () throws Namingexception, sqlexception{Context ctx = new InitialContext (); DataSource ds = (DataSource) ctx.lookup ("Java:comp/env/jndi/mybatis"); Connection conn = Ds.getconnection (); System.out.println (conn.isclosed ()); }
4) Invoking the load Jndi mode in the JSP, cannot be tested directly with the main method and must be called from the JSP by the boot container:
Testpageaccessurl test = new Testpageaccessurl (); Test.testjndi ();
Second type: Local configuration (not recommended).
1) within Tomcat's Server.xml
<context path= "/demo_jndi" docbase= "/demo_jndi" > <resource name= "jndi/mybatis" type= "Javax.sql.Da Tasource "Driverclassname=" Com.mysql.jdbc.Driver "maxidle=" 2 "maxwait=" "username=" "root" Password= "123456" url= "jdbc:mysql://localhost:3306/appdb" maxactive= "4"/> </Context>
Other configurations are the same as the first way.
The third type: local configuration.
1) Create a new context.xml under the meta-info of the project. Join:
<?xml version= "1.0" encoding= "UTF-8"?> <context> <resource name= "Jndi/mybatis" auth= "Container" type= "Javax.sql.DataSource" driverclassname= "Com.mysql.jdbc.Driver" url= "Jdbc:mysql://localhost:3306/appdb" username = "Root" password= "123456" Maxactive= " " maxidle= "Ten" maxwait= "10000"/> </context>
Other configurations are the same as the first way.
Summary: If you want to configure the local, we recommend a third way, so do not rely on Tomcat. However, it is recommended to use the first way, although relying on Tomat, but is global, and can be configured
Multiple. It is convenient for later switching.
Resource references added in the project's Web. XML are optional.
Three ways to configure Tomcat under Jndi