`
zhao870420le
  • 浏览: 9485 次
  • 性别: Icon_minigender_1
  • 来自: 青岛
社区版块
存档分类
最新评论

如果你还在使用jdbc直连,拜托,用连接池吧,so easy!

    博客分类:
  • java
阅读更多

请注意: 这里只使用Tomcat下的连接池.我们不需要对基目录修改.我们在eclipse下的工程目录配置.增加可移植性.

 

No.1:打开目录,找到WebRoot,好的,我们再找其子目录.OK,你发现了META-INF 和WEB-INF(当然大家都知道)

 

我们在META-INF (一定看清了是META-INF!!这很关键,不然一会运行时,会让你报错报的很空虚,很寂寞~)下建立

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true" crossContext="true">
<Resource name="jdbc/orcl"    
   auth="Container"
   type="javax.sql.DataSource"
   maxActive="4"
   maxIdle="2"
   maxWait="3000"
   username="scott"
   password="scott"
   driverClassName="oracle.jdbc.driver.OracleDriver"
   url="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
</Context> 	
 

No.2

修改一下WEB-INF下的web.xml

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

	<resource-ref>
		<description>DB Connection</description>
		<res-ref-name>jdbc/orcl</res-ref-name>
		<res-type>javax.sql.DataSource</res-type>
		<res-auth>Container</res-auth>
	</resource-ref>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>
 

No.3

 

下面的大家都会背了.

 

<!doctype html public "-//w3c//dtd html 4.0 transitional//en"    
 "http://www.w3.org/TR/REC-html40/strict.dtd">
<%@ page import="java.sql.*"%>
<%@ page import="javax.sql.*"%>
<%@ page import="javax.naming.*"%>
<%@ page session="false"%>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title></title>
		<%
			DataSource ds = null;
			Connection conn = null;
			Statement stmt = null;
			ResultSet rs = null;
			try {
				InitialContext ctx = new InitialContext();
				ds = (DataSource) ctx.lookup("java:comp/env/jdbc/orcl");
				conn = ds.getConnection();
				stmt = conn.createStatement();
				String strSql = " select * from t_user";
				rs = stmt.executeQuery(strSql);
				while (rs.next()) {
					out.println("<br/>id : "+rs.getString(1));
					out.println("name : "+rs.getString(2));
					out.println("<hr/>");
				}
			} catch (Exception ex) {
				out.print(ex.getMessage());
				ex.printStackTrace();
			}finally{
				stmt.close();
				conn.close();
			}
		%>
	</head>
	<body>
	</body>
</html>

 

No.4

 

打完收工,回家休息了.

<如果你还有人性,别忘了把驱动jar包放在tomcat/lib下>

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics