Tomca:8 + Mysql5 + JNDI + Eclipse4 配置数据源

来源:互联网 发布:linux连不通数据库端口 编辑:程序博客网 时间:2024/04/30 22:55

1:在eclipse 中建立一个动态web 项目

2:在WebContent -> META-INF 下建立一个content.xml

content.xml内容如下:


<?xml version="1.0" encoding="UTF-8"?>
<Context>                           
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <WatchedResource>${catalina.base}/conf/web.xml</WatchedResource>
 <Resource name="jdbc/userinfo" auth="Container"
type="javax.sql.DataSource" 
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/javaee"
username="root" password="root" maxActive="5"
maxIdle="2" maxWait="10000"/>
</Context>


3:在WebContent -> WEB-INF 下建立一个web.xml,内容如下


<?xml version="1.0" encoding="GBK"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   version="2.5"> 

<resource-ref>
    <description>MySqlDS</description>
    <res-ref-name>jdbc/userinfo</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

<welcome-file-list>
<welcome-file>GetDataFromTomcat.jsp</welcome-file>
</welcome-file-list>
</web-app>

4:在WebContent 建立一个测试用的  jsp文件,内容如下:


test.jsp

<%@ page language="java" contentType="text/html; charset=GBK"
    pageEncoding="GBK"%>
<%@ page import="javax.naming.*,java.sql.*,javax.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=GBK">
<title>get Data from Mysql via Tomcat</title>
</head>
<body>
<%
//初始化Context,使用InitialContext初始化Context
Context ctx=new InitialContext(); 
/*
通过JNDI查找数据源,该JNDI为java:comp/env/jdbc/dstest,分成两个部分
java:comp/env是Tomcat固定的,Tomcat提供的JNDI绑定都必须加该前缀
jdbc/dstest是定义数据源时的数据源名
*/
DataSource ds=(DataSource)ctx.lookup("java:comp/env/jdbc/userinfo");
//获取数据库连接
Connection conn=ds.getConnection();
//获取Statement
Statement stmt=conn.createStatement();
//执行查询,返回ResulteSet对象
ResultSet rs=stmt.executeQuery("select * from userspasswd");
while(rs.next())
{
out.println(rs.getString(1) 
+ "\t" + rs.getString(2) + "<br/>");
}
%>
</body>
</html>


5. 在 MySQL  javaee库里中建立一个表userspasswd。


6.在eclipse以run on server方式,选择tomcat8,就可以了。

7.也可以 按 WAR包输出,部署到tomcat中,然后执行 http://localhost:8080/<你的引用名字>/test.jsp


上述过程已调试通过


0 0
原创粉丝点击