Tomcat连接池配置+myeclipse
首先配置tomcat 中的配置文件 (试用于全局性的资源)
tomcat--conf--context.xml
例1:在context中配置
<Environment name="news" value="hello JNDI" type="java.lang.String"/>
在jsp中使用,通过Context的实例的lookup方法找到news这个名字并将其value值读取出来。
<% Context ctx =new InitialContext(); String testjndi=(String)ctx.lookup("java:comp/env/news"); out.println(testjndi); %>
例子2:配置数据库通过tomcat的连接,则需要将原项目lib中的jar包方到tomcat的lib中。(注意区分mysql和mssql不同的jar包)
在context中添加一下代码,name是自定义的其他是固定用法。
<Resource name="jdbc/demo" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="root" password="root" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test?autoReconnect=true"/>
一下是具体的使用,context------source.getConnection();其他部分与数据库直接操作相同。这一段例子是查询user表中name字段并显示出来。<% Connection connection = null; PreparedStatement titlesQuery = null; ResultSet rs = null; try { Context ic = new InitialContext(); DataSource source = (DataSource) ic .lookup("java:comp/env/jdbc/demo"); connection = source.getConnection(); titlesQuery = connection .prepareStatement("SELECT * FROM user "); rs = titlesQuery.executeQuery(); if (rs!=null){ while(rs.next()){ out.println(rs.getString("name")); out.println("<br/>"); } } } catch (SQLException exception) { exception.printStackTrace(); } catch (NamingException namingException) { namingException.printStackTrace(); } finally { if (rs != null) rs.close(); if (titlesQuery != null) titlesQuery.close(); if (connection != null) connection.close(); } %>