我正在使用JNDI处理数据库连接。我确定部署很好。因为当我在下面的JSP中对其进行测试时,它可以正常工作。
</head>
<body>
<%
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)envCtx.lookup("jdbc/airlineticket");
Connection conn = ds.getConnection();
out.println(conn);
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>
但是当我使用ConnectionFactory类时,会出现错误: ConnectionFactory无法解决。我只是将连接代码放在ConnectionFactory类中,为什么会这样? ConnectionFactory类:
package com.db;
import javax.naming.*;
import java.sql.*;
import org.apache.tomcat.jdbc.pool.DataSource;
public class ConnectionFactory {
private ConnectionFactory() {};
public static Connection getConnection()
{
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)envCtx.lookup("jdbc/airlineticket");
return ds.getConnection();
}
catch (NamingException e)
{
System.out.print("connection failed");
return null;
}
catch(SQLException e)
{
e.printStackTrace();
return null;
}
}
}
测试JSP:
<%@ page language="java" import="java.util.*,com.db.ConnectionFactory" pageEncoding="UTF-8"%>
</head>
<body>
<%
try {
Connection conn = ConnectionFactory.getConnection();
out.println(conn);
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>
web.xml(/WEB-INF/web.xml):
<resource-ref>
<res-ref-name>jdbc/airlineticket</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
context.xml(/META-INF/context.xml):
<Context>
<Resource name="jdbc/airlineticket"
auth="Container"
type="javax.sql.DataSource"
username="Manager"
password="123456"
driverClassName="org.mariadb.jdbc.Driver"
url="jdbc:mariadb://localhost:3306/airlineticket"
maxActive="50"
masIdle="20"> </Resource>
</Context>
答案 0 :(得分:0)
JSP将自动重新编译...而Java文件则每次都必须构建和部署,除非您正在使用JRebel。...
如果您已经完成此操作,希望查看您的完整日志...