我一直在尝试将Tomcat配置为在IntelliJ中访问MySQL数据库,但没有取得多大成功。
我已经放置了mysql-connector-java-5.1.20。 jar到Tomcat8.5 / lib /
这是我的context.xml文件,放在WEB-INF / lib /中
<Context>
<WatchedResources>WEB-INF/web.xml</WatchedResources>
<Resourse name="jdbc/web_student_tracker"
auth="Container" type="javax.sql.DataSource"
maxActive="20" maxIdle="5" maxWait="10000"
username="webstudent" password="webstudent"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/web_student_tracker"/>
</Context>
Web.xml文件位于WEB-INF /
中 <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<resource-ref>
<description>MySQL Data Source Example</description>
<res-ref-name>jdbc/web_student_tracker</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
这就是我的servlet的样子
@WebServlet(name = "TestServlet", urlPatterns = {"/testServlet","/a"})
public class TestServlet extends HttpServlet {
//define datasource/connection pool for resource injection
@Resource(name="jdbc/web_student_tracker")
private DataSource dataSource;
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
//set the printwriter
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
//get a connection to the database
Connection myConn =null;
Statement myStmt = null;
ResultSet myRs = null;
try {
// create a sql statements
myConn = dataSource.getConnection(); // fails here
// execute sql query
String sql = "select * from student";
myStmt = myConn.createStatement();
//process the result set
myRs = myStmt.executeQuery(sql);
while(myRs.next()) {
String email = myRs.getString("email");
out.println(email);
}
}
catch ( Exception exc) {
exc.printStackTrace();
}
}
}
当我尝试从数据源获取连接时,我得到以下异常:
java.sql.SQLException: Cannot create JDBC driver of class '' for connect URL
'null'
...
Caused by: java.sql.SQLException: No suitable driver
at java.sql.DriverManager.getDriver(DriverManager.java:315)
...
我做错了什么或错过了什么? 感谢您的时间和帮助!