Tomcat8.5配置JNDI数据源详细过程
Tomcat8.5配置JNDI数据源详细过程
初次学习,发现了很多问题,参照了很多博友,最终解决问题,分享大家。
-
第一步、下载数据库的JDBC驱动,解压后放到Tomcat文件的lib文件下。
-
第二步、在eclipse中,创建web项目,新建项目选址Dynamic Web Project
-
第三步、将数据库的JDBC驱动解压复制到项目的WebContent/WEB-INF/lib文件下,并建立路径。如下图:
-
第四步、项目中导入Tomcat包,(注意前提是eclipse已经导入了Tomcat),方法是:鼠标放在项目根目录,鼠标右击,选择Build Path -> Configure Build Path
-
第五步、
在WebContent在新建jsp文件,内容如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page import="javax.naming.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
out.print("MySQL 数据源测试开始..." + "<br/>");
DataSource ds = null;
Connection conn = null;
try {
Context ctx = new InitialContext();
String DSNAME = "java:comp/env/jdbc/testjndi";
ds = (DataSource) ctx.lookup(DSNAME);
conn = ds.getConnection();
%>
<%
conn.close();
out.print("MySQL 数据源连接成功!");
} catch (Exception e) {
out.print("连接失败,原因是:" + e.getMessage());
e.printStackTrace();
}
%>
</body>
</html>
WebContent/lib/web.xml文件配置如下:jdbc/testjndi必须与jsp中的一致
没有web.xml文件,鼠标右击项目根目录:Java EE Tools -> Generate Deployment Descripter Stub (鼠标点击即可)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>biaoDaShiLanguage</display-name>
<description>welcome to tomcat</description>
<!--需要添加的内容 -->
<resource-ref>
<res-ref-name>jdbc/testjndi</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
- 第六步、配置context文件,Tomcat4.0以后拥有独立的Context.xml 文件,我们要配置这个独立的Context.xml文件。
在eclipse 项目窗口中展开Server是,打开context.xml 文件,如下:
MySql数据库的配置
<Resource name="jdbc/mldn" //表示数据源的名称
auth="Container" //表示由容器负责资源的连接
type="javax.sql.DataSource" //表示对象,数据源上每一个绑定的都是DataSource
maxActive="100" //表示最大连接数
maxIdle="30" //表示最小维持数
maxWait="10000" //最大等待时间
username="root"
password="1234"
driverClassName="org.gjt.mm.mysql.Driver"
url="jdbc:mysql://localhost:3306/mldn"/>
Oracle数据库配置
<Resource name="jdbc/mldn" //表示数据源的名称
auth="Container" //表示由容器负责资源的连接
type="javax.sql.DataSource" //表示对象,数据源上每一个绑定的都是DataSource
maxActive="100" //表示最大连接数
maxIdle="30" //表示最小维持数
maxWait="10000" //最大等待时间
username="scoot"
password="oraceladmin"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:mldn"/>
保存完所有配置的文件,可以运行jsp了