Eclipse Java EE的tomcat使用小结

在eclipse里面配置了tomcat 6.0.23之后, 会自动生成一个Servers的工程

里面都是tomcat的配置文件, 可以在这里直接修改配置文件, 而且eclipse的工程也不会打包发布到tomcat安装文件夹中

也就是说, eclipse不会破坏原来的tomcat安装文件夹, 在tomcat目录下的webapps中也看不到你在eclipse下运行的工程

我在配置DataSource的时候, 遇到了这个问题, 现在将配置过程写下来, 给大家提供一个参考

1. 在server.xml中配置DataSource

在eclipse的工程Servers中, 修改配置文件Tomcat v6.0 Server at localhost-config\server.xml, 在<Host>之间添加下面的DataSource配置

<Context docBase="Test" path="/Test"
  reloadable
="true" source="org.eclipse.jst.jee.server:Test">
<Resource auth="Container" driverClassName="com.mysql.jdbc.Driver"
      maxActive
="8" maxIdle="4" name="jdbc/test" type="javax.sql.DataSource"
      url
="jdbc:mysql://localhost:3306/test" username="root" password="your password"/>
</Context>

网上很多人说, 需要将mysql的jdbc驱动拷贝到tomcat目录的lib下, 但我在实际操作中发现, 没有必要

注意:

docBase="Test" path="/Test"      必须和你的项目名称一致
name
="jdbc/test" 这个名字可以随便改, 之后通过jndi查找DataSource的名字 

2. 配置项目中的web.xml, 添加下面配置

<resource-ref>
<description>
Resource reference to a factory for java.sql.Connection
instances that may be used for talking to a particular
database that is configured in the configurartion for the web application.
</description>
<res-ref-name>jdbc/test</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

3. 写一个测试的jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding
="ISO-8859-1"%>
<%@ page import="java.util.*, 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=ISO-8859-1">
<title>DataSource Demo</title>
</head>
<body>
<%
Context initCtx
= new InitialContext();
Context envCtx
= (Context) initCtx.lookup("java:comp/env");
DataSource ds
= (DataSource) envCtx.lookup("jdbc/test");

Connection conn
= ds.getConnection();
out.println(
"conncetion Ok<br/>");
Statement stmt
= conn.createStatement();
out.println(
"Executing statement.<br/>");
ResultSet rset
= stmt.executeQuery("select * from person");
out.println(
"Results:<br/>");
int numcols = rset.getMetaData().getColumnCount();
while(rset.next()) {
for(int i=1;i<=numcols;i++) {
out.print(
" &emsp;" + rset.getString(i));
}
out.println(
"<br/>");
}
conn.close();
%>
</body>
</html>

我这里连接的是mysql的数据库test, 在我的test下有张表是person

运行这个jsp, 可以看到person表中的数据被取出来了

运行结果大概是这样的

conncetion Ok
Executing statement.
Results:
 1 aaa 21 address001
 2 bbb 51 address002
原文地址:https://www.cnblogs.com/icejoywoo/p/2042847.html