tomcat使用JDNI配置信息和使用信息。用于JDBC连接池
时间:2021-07-01 10:21:17
帮助过:17人阅读
-->
<Resource name="jdbc/dataSource"
factory="org.apache.naming.factory.BeanFactory"
type="com.mchange.v2.c3p0.ComboPooledDataSource"
jdbcUrl="jdbc:mysql://127.0.0.1:3306/demo"
driverClass="com.mysql.jdbc.Driver"
user="guodaxia"
password="961012gz"
acquireIncrement="3"
initialPoolSize="10"
/>
</Context>
package cn.itcast.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
public class AServlet
extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L
;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
/*
* 1、创建JNDI的上下文对象
*/
Context context=
new InitialContext();
// //2、查询进入入口
// context=(Context) context.lookup("java:comp/env");
// //3、查询创建指定bean
// DataSource dataSource=(DataSource) context.lookup("jdbc/dataSource");
//第二和第三步骤可以合为一步
DataSource dataSource=(DataSource) context.lookup("java:comp/env/jdbc/dataSource"
);
//4、得到Connection对象
Connection conn=
dataSource.getConnection();
System.out.println(conn);
} catch (NamingException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html"
);
PrintWriter out =
response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">"
);
out.println("<HTML>"
);
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>"
);
out.println(" <BODY>"
);
out.print(" This is "
);
out.print(this.getClass());
out.println(", using the POST method"
);
out.println(" </BODY>"
);
out.println("</HTML>"
);
out.flush();
out.close();
}
}
所用jar:
tomcat使用JDNI配置信息和使用信息。用于JDBC连接池
标签: