在 JSP 中使用 MySQL 连接到 Tomcat 服务器
所以我试图让一些教程代码正常工作,但我陷入了困境。我在 Eclipse 中有一个 Web 应用程序,其中包含一个 DBConnector.java 文件、一个 Tomcat 6 服务器(本地)和一个简短的 JSP 脚本:
package com.atj.db;
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.sql.DataSource;
public class DBConnector {
private static DBConnector connector_ = null;
public static DBConnector getInstance() throws Exception {
if (connector_ == null) {
connector_ = new DBConnector();
}
return connector_;
}
public Connection getConnection() throws Exception {
// Get DataSource
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx
.lookup("java:comp/env/jdbc/mydatabase");
Connection c = ds.getConnection();
return c;
}
public String getFirstName() throws Exception {
String first = "";
try {
Connection con = getConnection();
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employees");
while (res.next()) {
first = res.getString("first");
System.out.println(first);
}
con.close();
} catch (SQLException s) {
System.out.println("SQL code does not execute.");
}
return first;
}
}
我正在尝试发布 JSP,但 StackOverflow 正在解析我的 HTML...呃。 .抱歉..我该如何逃避这个问题?下面是教程代码:
这是一个非常短的 JSP 脚本,其中包含2条主线:
DBConnector dbConn = DBConnector.getInstance();
String name = dbConn.getFirstName(); <---error line
无论如何,当我在浏览器中打开它时,它会在控制台上打印“SQL代码不执行”。我可以看到当抛出 SQLException 时会发生这种情况。我将其调试到 getConnection 中的这一行:
DataSource ds = (DataSource) ctx
.lookup("java:comp/env/jdbc/mydatabase");
执行此行后,ctx 填充了大部分空值(除了 id)
然后这一行:
Connection c = ds.getConnection();
抛出 SQLException,并且控制立即交给 catch 块。
另外,Eclipse 对此导入发出警告,表示“由于所需库 /System/Library/Frameworks/JavaVM.framework/Versions/1.4.2/Classes/classes.jar 的限制,无法访问类型 DataSource”
import javax.sql.DataSource; //<---Eclipse is complaining about this line, but still compiling
这是项目树:
project
Java Resources: src
com.atj.project
DBConnector.java
Libraries
EAR Libraries
JRE System Library
Web App Libraries
mysql-connector-java-5.1.14-bin.jar
Web Content
META-INF
content.xml
MANIFEST.MF
Web-INF
lib
mysql-connector-java-5.1.14-bin.jar
web.xml
db.jsp
Servers
Tomcat v6.0 server at localhost-config
catalina.policy
catalina.properties
content.xml
server.xml
tomcat-users.xml
web.xml
非常感谢任何帮助
编辑-这是我的 .xml 文件
content.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!-- Specify a JDBC datasource -->
<Resource name="jdbc/mydatabase"
auth="Container"
type="javax.sql.DataSource"
username="demo"
password="demo"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://www.coincan.net:3306/demo?autoReconnect=true"
validationQuery="select 1"
maxActive="2"
maxIdle="1"/>
</Context>
(new)web.xml。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp_ID">
<display-name>db</display-name>
<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>
<resource-ref>
<description>mydatabase</description>
<res-ref-name>jdbc/mydatabase</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
So I'm trying to get some tutorial code working, and I'm stuck. I have a web application in Eclipse which consists of a DBConnector.java file, a Tomcat 6 server (local), and a short JSP script:
package com.atj.db;
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.sql.DataSource;
public class DBConnector {
private static DBConnector connector_ = null;
public static DBConnector getInstance() throws Exception {
if (connector_ == null) {
connector_ = new DBConnector();
}
return connector_;
}
public Connection getConnection() throws Exception {
// Get DataSource
Context ctx = new InitialContext();
DataSource ds = (DataSource) ctx
.lookup("java:comp/env/jdbc/mydatabase");
Connection c = ds.getConnection();
return c;
}
public String getFirstName() throws Exception {
String first = "";
try {
Connection con = getConnection();
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM employees");
while (res.next()) {
first = res.getString("first");
System.out.println(first);
}
con.close();
} catch (SQLException s) {
System.out.println("SQL code does not execute.");
}
return first;
}
}
I'm trying to post the JSP, but StackOverflow is parsing my HTML...argh..sorry..how do I escape this? Here is the tutorial code:
It's a very short JSP script with the 2 main lines:
DBConnector dbConn = DBConnector.getInstance();
String name = dbConn.getFirstName(); <---error line
Anyway, when I open this in a browser, it prints "SQL Code does not execute" to the console. I can see this happens when an SQLException gets thrown. I debugged this down to this line in getConnection:
DataSource ds = (DataSource) ctx
.lookup("java:comp/env/jdbc/mydatabase");
After executing this line, ctx is filled with mostly null values (except for id)
And then this line:
Connection c = ds.getConnection();
throws the SQLException, and control is immediately handed to the catch block.
Also, Eclipse is giving me a warning on this import, saying "The type DataSource is not accessible due to a restriction on the required library /System/Library/Frameworks/JavaVM.framework/Versions/1.4.2/Classes/classes.jar
import javax.sql.DataSource; //<---Eclipse is complaining about this line, but still compiling
Here is the project tree:
project
Java Resources: src
com.atj.project
DBConnector.java
Libraries
EAR Libraries
JRE System Library
Web App Libraries
mysql-connector-java-5.1.14-bin.jar
Web Content
META-INF
content.xml
MANIFEST.MF
Web-INF
lib
mysql-connector-java-5.1.14-bin.jar
web.xml
db.jsp
Servers
Tomcat v6.0 server at localhost-config
catalina.policy
catalina.properties
content.xml
server.xml
tomcat-users.xml
web.xml
Any help is greatly appreciated.
Edit-Here are my .xml files
content.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<!-- Specify a JDBC datasource -->
<Resource name="jdbc/mydatabase"
auth="Container"
type="javax.sql.DataSource"
username="demo"
password="demo"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://www.coincan.net:3306/demo?autoReconnect=true"
validationQuery="select 1"
maxActive="2"
maxIdle="1"/>
</Context>
(new)web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp_ID">
<display-name>db</display-name>
<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>
<resource-ref>
<description>mydatabase</description>
<res-ref-name>jdbc/mydatabase</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我觉得你还差得很远。
你没有说是否有 META-INF/context.xml 文件来在 Tomcat 中设置数据源池;你需要一个。
你没有说是否在 web.xml 中声明了数据源;你应该。
看看这些是否能解决你的问题。
您可能还想阅读此。我认为 JNDI 名称应该是“jdbc/mydatabase”。
您肯定没有在您的方法中正确关闭资源;您根本不关闭 ResultSet,并且应该关闭 finally 块中的所有内容。
将其添加到 web.xml 的末尾:
I think you're still pretty far off.
You don't say if you have a META-INF/context.xml file to set up the data source pool in Tomcat; you need one.
You don't say if you declare the data source in your web.xml; you should.
See if those sort you out.
You might also want to read this. I think the JNDI name ought to be "jdbc/mydatabase".
You certainly aren't closing your resources properly in your method; you don't close the ResultSet at all, and you should close everything in a finally block.
Add this at the end of your web.xml: