Bom dia pessoal !
Estou estudando a implementação de Pool de Conexões com o Tomcat 6 e não estou conseguindo fazer uma conexão porque a minha aplicação está lançando uma NamingException e não estou conseguindo entender o por quê do problema.
Para configurar o DataSource eu segui a documentação oficial do Tomcat (http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html) além de acompanhar outro tutorial publicado no site da DevMedia (http://www.devmedia.com.br/articles/viewcomp.asp?comp=4113).
Primeiro eu copiei o j-connector do MySQL do diretório $TOMCAT_HOME/lib e implementei o resource do Pool dentro do arquivo context.xml no diretório META-INF/ da minha aplicação:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/aplicacaoExemplo">
<Resource
name="jdbc/ExemploPool"
auth="Container"
type="javax.sql.DataSource"
maxActive="100"
maxIdle="30"
maxWait="10000"
username="felipeassis"
password="123mudar"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/exemplo_bd?autoReconnect=true"
/>
</Context>
Em seguida, configurei a referência ao Resource no web.xml da minha aplicação:
<?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">
<description>Aplicação de exemplo da utilização de Pool de Conexões com MySQL e Tomcat 6</description>
<servlet>
<servlet-name>ConsultaUsuariosServlet</servlet-name>
<servlet-class>org.felipeassis.servlet.ConsultaUsuariosServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ConsultaUsuariosServlet</servlet-name>
<url-pattern>/ConsultaUsuariosServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<resource-ref>
<description>Datasource de exemplo para MySQL</description>
<res-ref-name>jdbc/ExemploPool</res-ref-name>
<res-type>Container</res-type>
</resource-ref>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Para testar a conexão implementei a seguinte Servlet:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.felipeassis.servlet;
import java.io.*;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.ResultSet;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
/**
*
* @author felipeassis
*/
public class ConsultaUsuariosServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Context ctxt = null;
Connection conn = null;
DataSource ds = null;
Statement stmt = null;
ResultSet rs = null;
StringBuffer sb = new StringBuffer();
PrintWriter out = response.getWriter();
try{
// estabelecendo conexão com o banco
ctxt = new InitialContext();
ds = (DataSource) ctxt.lookup("jdbc/ExemploPool");
conn = ds.getConnection();
// Preparando e executando consulta
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM usuarios");
//Montando página e listagem
response.setContentType("text/html");
response.setCharacterEncoding("ISO-8859-1");
sb.append("<html><head><title>Exemplo - Criando Pool de Conexões</title></head>");
sb.append("<body><table width='100%' cellpadding='3' cellspacing='3' border='0'>");
sb.append("<thead><tr><th colspan='6'></th></tr><tr>");
sb.append("<<th>ID</th>");
sb.append("<th>Sexo</th>");
sb.append("<th>Nome</th>");
sb.append("<th>Sobrenome</th>");
sb.append("<th>Login</th>");
sb.append("<th>Senha</th>");
sb.append("</tr></thead>");
sb.append("<tbody>");
while(rs.next()){
sb.append("<tr>");
sb.append("<td>" + rs.getInt("id") + "</td>");
sb.append("<td>" + rs.getCharacterStream("sexo") + "</td>");
sb.append("<td>" + rs.getString("nome") + "</td>");
sb.append("<td>" + rs.getString("sobrenome") + "</td>");
sb.append("<td>" + rs.getString("login") + "</td>");
sb.append("<td>" + rs.getString("senha") + "</td>");
sb.append("</tr>");
}
sb.append("</tbody></table></body></html>");
out.println(sb.toString());
} catch(NamingException e){
System.err.println("O DataSource configurado não foi encontrado: " + e.getMessage());
e.printStackTrace();
} catch(SQLException e){
System.err.println("Erro ao executar consulta: " + e.getMessage());
} finally {
try{
if(rs != null){
rs.close();
}
} catch (SQLException e){ }
try{
if(stmt != null){
stmt.close();
}
} catch (SQLException e){ }
try{
if(conn != null){
conn.close();
}
} catch (SQLException e){ }
sb = null;
out.close();
}
}
}
Revirei, reescrevi todo o código e não consegui descobrir o motivo da NamingException. Ao rodar a Servlet ele retorna a seguinte mensagem capturada no Try/Catch:
O DataSource configurado não foi encontrado: Name jdbc is not bound in this Context
javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
O que está faltando ou está errado na minha implementação?