Java中的Tomcat数据源JNDI示例

Welcome to Tomcat DataSource JNDI Example Tutorial. We looked at the JDBC DataSource in the last tutorial and learned how to use that in standalone java application.

欢迎使用Tomcat DataSource JNDI示例教程。 我们在上一教程中查看了JDBC DataSource ,并学习了如何在独立的Java应用程序中使用它。

Tomcat数据源JNDI (Tomcat DataSource JNDI)

tomcat datasource, jndi example, tomcat jndi, jndi tutorial

Actual benefit of DataSource comes when we use it with a JNDI Context. For example, connection pool in a web application deployed in a servlet container. Most of the popular servlet containers provide built-in support for DataSource through Resource configuration and JNDI context. This helps us in creating and using DataSource connection pool with just few lines of configuration. This tutorial is aimed to provide Tomcat DataSource JNDI configuration example.


当我们将其与JNDI Context一起使用时,DataSource的实际好处就来了。 例如,Web应用程序中的连接池部署在Servlet容器中。 大多数流行的servlet容器通过资源配置和JNDI上下文提供对DataSource的内置支持。 这有助于我们通过几行配置来创建和使用DataSource连接池。 本教程旨在提供Tomcat DataSource JNDI配置示例。

Apache Tomcat provide three ways to configure DataSource in JNDI context.

Apache Tomcat提供了三种在JNDI上下文中配置DataSource的方法。

  1. Application context.xml – This is the easiest way to configure DataSource, all we need is a context.xml file in META-INF directory. We have to define Resource element in the context file and container will take care of loading and configuring it. The approach is simple but it has some drawbacks;
    • Since the context file is bundled with the WAR file, we need to build and deploy new WAR for every small configuration change. Same issue comes if your application works in distributed environment or your application needs to be deployed in different testing environments such as QA, IT, PROD etc.
    • The datasource is created by container for the application usage only, so it can’t be used globally. We can’t share the datasource across multiple applications.
    • If there is a global datasource (server.xml) defined with same name, the application datasource is ignored.

    应用程序context.xml –这是配置DataSource的最简单方法,我们需要的是META-INF目录中的context.xml文件。 我们必须在上下文文件中定义Resource元素,容器将负责加载和配置它。 该方法很简单,但是有一些缺点。
    • 由于上下文文件与WAR文件捆绑在一起,因此我们需要为每个小的配置更改构建并部署新的WAR。 如果您的应用程序在分布式环境中运行,或者您的应用程序需要部署在不同的测试环境(例如QA,IT,PROD等)中,也会出现同样的问题。
    • 数据源是由容器创建的,仅供应用程序使用,因此不能全局使用。 我们不能在多个应用程序之间共享数据源。
    • 如果存在使用相同名称定义的全局数据源(server.xml),则将忽略应用程序数据源。
  2. Server context.xml – If there are multiple applications in the server and you want to share DataSource across them, we can define that in the server context.xml file. This file is located in apache-tomcat/conf directory. The scope of server context.xml file is application, so if you define a DataSource connection pool of 100 connections and there are 20 applications then the datasource will be created for each of the application. This will result in 2000 connections that will obviously consume all the database server resources and hurt application performance.

    服务器context.xml –如果服务器中有多个应用程序,并且您希望在它们之间共享数据源,则可以在服务器context.xml文件中对其进行定义。 该文件位于apache-tomcat/conf目录中。 服务器context.xml文件的范围是应用程序,因此,如果您定义一个包含100个连接的数据源连接池,并且有20个应用程序,则将为每个应用程序创建数据源。 这将导致2000个连接,这显然会消耗所有数据库服务器资源,并损害应用程序性能。
  3. server.xml and context.xml – We can define DataSource at global level by defining them in the server.xml GlobalNamingResources element. If we use this approach, then we need to define a ResourceLink from context.xml file of server or application specific. This is the preferred way when you are looking to share a common resource pool across multiple applications running on the server. Regarding resource link, whether to define it at server level context xml file or application level depends on your requirement.

    server.xml和context.xml –我们可以通过在server.xml GlobalNamingResources元素中定义它们来在全局级别定义DataSource。 如果使用这种方法,则需要从特定于服务器或应用程序的context.xml文件定义一个ResourceLink 。 当您希望在服务器上运行的多个应用程序之间共享公用资源池时,这是首选方法。 关于资源链接,是在服务器级别的上下文xml文件还是在应用程序级别定义它取决于您的要求。

Let’s head over to the Tomcat DataSource JNDI example in java web application.

让我们来看一下Java Web应用程序中的Tomcat DataSource JNDI示例。

For the test data setup, please refer to my last article about JDBC DataSource Example.

对于测试数据设置,请参考我关于JDBC DataSource Example的上一篇文章。

Tomcat数据源JNDI配置示例– server.xml (Tomcat DataSource JNDI Configuration Example – server.xml)

Add below code in the tomcat server.xml file. The code should be added in the GlobalNamingResources element. Also make sure that database driver is present in the tomcat lib directory, so in this case mysql jdbc jar have to be present in the tomcat lib.

在tomcat server.xml文件中添加以下代码。 该代码应添加到GlobalNamingResources元素中。 还要确保tomcat lib目录中存在数据库驱动程序,因此在这种情况下,tomcat lib中必须存在mysql jdbc jar。

<Resource name="jdbc/MyDB" 
      global="jdbc/MyDB" 
      auth="Container" 
      type="javax.sql.DataSource" 
      driverClassName="com.mysql.jdbc.Driver" 
      url="jdbc:mysql://localhost:3306/UserDB" 
      username="pankaj" 
      password="pankaj123" 
      
      maxActive="100" 
      maxIdle="20" 
      minIdle="5" 
      maxWait="10000"/>

Here we are creating JNDI context with name as jdbc/MyDB which is a type of DataSource. We are passing database configurations in url, username, password and driverClassName attribute. Connection pooling properties are defined in maxActive, maxIdle and minIdle attributes.

在这里,我们正在创建名称为jdbc/MyDB JNDI上下文,这是一种数据源。 我们通过url,用户名,密码和driverClassName属性传递数据库配置。 连接池属性在maxActive,maxIdle和minIdle属性中定义。

Tomcat数据源JNDI资源链接配置– context.xml (Tomcat DataSource JNDI Resource Link Configuration – context.xml)

Add below code in the server context.xml file.

在服务器context.xml文件中添加以下代码。

<ResourceLink name="jdbc/MyLocalDB"
                global="jdbc/MyDB"
                auth="Container"
                type="javax.sql.DataSource" />

Notice that resource link name is different than global link, we have to use this name in our java program to get the DataSource.

请注意,资源链接名称不同于全局链接,我们必须在Java程序中使用此名称来获取数据源。

Tomcat数据源JNDI示例 (Tomcat DataSource JNDI Example)

Create a dynamic web application with name JDBCDataSourceTomcat and then create a Servlet with below code.

创建一个名称为JDBCDataSourceTomcat的动态Web应用程序,然后使用以下代码创建一个Servlet。

package com.journaldev.jdbc.datasource;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

@WebServlet("/JDBCDataSourceExample")
public class JDBCDataSourceExample extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Context ctx = null;
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;
		try{
			ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/MyLocalDB");
			
			con = ds.getConnection();
			stmt = con.createStatement();
			
			rs = stmt.executeQuery("select empid, name from Employee");
			
			PrintWriter out = response.getWriter();
            response.setContentType("text/html");
            out.print("<html><body><h2>Employee Details</h2>");
            out.print("<table border=\"1\" cellspacing=10 cellpadding=5>");
            out.print("<th>Employee ID</th>");
            out.print("<th>Employee Name</th>");
            
            while(rs.next())
            {
                out.print("<tr>");
                out.print("<td>" + rs.getInt("empid") + "</td>");
                out.print("<td>" + rs.getString("name") + "</td>");
                out.print("</tr>");
            }
            out.print("</table></body><br/>");
            
            //lets print some DB information
            out.print("<h3>Database Details</h3>");
            out.print("Database Product: "+con.getMetaData().getDatabaseProductName()+"<br/>");
            out.print("Database Driver: "+con.getMetaData().getDriverName());
            out.print("</html>");
            
		}catch(NamingException e){
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}finally{
			try {
				rs.close();
				stmt.close();
				con.close();
				ctx.close();
			} catch (SQLException e) {
				System.out.println("Exception in closing DB resources");
			} catch (NamingException e) {
				System.out.println("Exception in closing Context");
			}
			
		}
	}

}

Notice that I am using Servlet 3 Annotation based configuration and it will work in Tomcat 7 or higher versions. If you are using lower version of Tomcat then you need to do some modifications to the servlet code, to remove WebServlet annotation and configure in web.xml file.

请注意,我正在使用基于Servlet 3注释的配置 ,它将在Tomcat 7或更高版本中工作。 如果使用的是较低版本的Tomcat,则需要对Servlet代码进行一些修改,以删除WebServlet注释并在web.xml文件中进行配置。

The part of servlet code that we are interested in;

我们感兴趣的servlet代码部分;

ctx = new InitialContext();
DataSource ds = (DataSource) ctx.lookup("java:/comp/env/jdbc/MyLocalDB");

This is the way to get the JNDI resources defined to be used by the application. We could have written it in this way too;

这是获取定义为由应用程序使用的JNDI资源的方法。 我们也可以这样写;

ctx = new InitialContext();
Context initCtx  = (Context) ctx.lookup("java:/comp/env");
DataSource ds = (DataSource) initCtx.lookup("jdbc/MyLocalDB");

I am also printing some database information to check which database we are connected.

我还在打印一些数据库信息,以检查我们连接了哪个数据库。

Now when you will run the application, you will see following output.

现在,当您运行应用程序时,将看到以下输出。

Let’s see how easy it is to switch the database server because we are using Tomcat DataSource. All you need is to change the Database properties. So if we have to switch to Oracle database, my Resource configuration will look like below.

让我们看看切换数据库服务器有多么容易,因为我们正在使用Tomcat DataSource。 您只需要更改数据库属性。 因此,如果必须切换到Oracle数据库,我的资源配置将如下所示。

<Resource name="jdbc/MyDB" 
      global="jdbc/MyDB" 
      auth="Container" 
      type="javax.sql.DataSource" 
      driverClassName="oracle.jdbc.driver.OracleDriver" 
      url="jdbc:oracle:thin:@localhost:1521:orcl" 
      username="hr" 
      password="oracle" 
      
      maxActive="100" 
      maxIdle="20" 
      minIdle="5" 
      maxWait="10000"/>

And when we restart the server and run the application, it will connect to Oracle database and produce below result.

当我们重新启动服务器并运行该应用程序时,它将连接到Oracle数据库并产生以下结果。

That’s all for Tomcat DataSource JNDI configuration example tutorial, you can define the resource in similar way in context.xml files too.

这就是Tomcat DataSource JNDI配置示例教程的全部内容,您也可以在context.xml文件中以类似方式定义资源。

翻译自: https://www.journaldev.com/2513/tomcat-datasource-jndi-example-java

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值