运行环境:MyEclipse8.5、Tomcat6.0、Oracle11g
Context配置:
<Resource     name="jdbc/oracle" auth="Container"
              type="javax.sql.DataSource" driverClassName="oracle.jdbc.OracleDriver"
              url="jdbc:oracle:thin:@10.88.23.39:1521:orcl"
              username="scott" password="tiger" maxActive="20" maxIdle="10"
              maxWait="-1">
</Resource> 
监听器配置:
public class DsListener1 implements ServletContextListener {
private ServletContext context = null;
public void contextDestroyed(ServletContextEvent sce) {
context.removeAttribute("ds");
}
public void contextInitialized(ServletContextEvent sce) {
/*
 * 对Servlet监听进行配置并初始化datasource信息
 */
context = sce.getServletContext();
DataSource ds = null;
Context envContext = null;
Context ctx = null; try {
ctx = new InitialContext();
envContext = (Context) ctx.lookup("java:comp/env");
ds = (DataSource) envContext.lookup("jdbc/oracle");
System.out.println("配置数据源完成...");
context.setAttribute("ds", ds); //把datasouce存入ServletContext中 } catch (NamingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} }
获取数据源建立数据库连接配置:
public class LoginAction extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8"); String userName = request.getParameter("userName");
String password = request.getParameter("password"); boolean loginPermit = false;
if (userName != null) {
// 获取数据源
DataSource ds = (DataSource) getServletContext().getAttribute("ds");
System.out.println(ds);//可以打印出ds
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
// 进行数据库的连接
try {
conn=ds.getConnection();
System.out.println(conn);//打印不出conn
stmt = conn.createStatement();
String sql = "SELECT * FROM uesrinfo";
rs = stmt.executeQuery(sql);
// 从数据库中查询是否是有效登录用户
while (rs.next()) {
if (userName.equalsIgnoreCase(rs.getString(2))) {
if (password.equalsIgnoreCase(rs.getString(2))) {
loginPermit = true;
break;
}
}
}
} catch (SQLException e) {
System.out.println(e.toString());
}// 关闭数据库连接
finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println(e.toString());
}
} if (loginPermit) {
request.getRequestDispatcher("home.view").forward(request,
response);
} else {
response.sendRedirect("login-error.html");
}
} else {
response.sendRedirect("login-error.html");
} } public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
初次运行时出现无法加载驱动,于是把数据库驱动的jar包copy进Tomcat的lib文件夹,
再次运行出现错误提示:
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (The Network Adapter could not establish the connection)。
我进行了打印,查看出错位置,进行数据库连接时conn打印不出。求大虾指教解决问题的办法!!!