Jasper Report - Pool de Conexoes [AJUDA]

3 respostas
rollei

Estou tentando fazer um relatorio teste, funcionar usando uma pool de conexoes (antes, eu estava utilizando uma conexao direta com o banco). Pois bem, dei uma pesquizada no forum e vi um post explicando +- como se faz isso. Estou tendo alguns problemas, aqui vai o codigo:

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/hibernate</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
    </resource-ref>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <servlet>
        <servlet-name>reportService</servlet-name>
        <servlet-class>report.ReportHibernate</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>reportService</servlet-name>
        <url-pattern>/reportService</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>
index.jsp
<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <a href="<%= request.getContextPath()%>/reportService">Link</a>
    </body>
</html>
PoolConnection.java
public class PoolConnection {

    /**
     * 
     * @return a connection from the connection pool
     * @throws java.lang.Exception
     */
    public Connection getConnection()
            throws Exception {

        // Buscar contexto JNDI
        Context ic = new InitialContext();
        // Solicitar o objeto Data Source
        DataSource ds = (DataSource) ic.lookup("jdbc/hibernate");
        // Obter uma conexao     
        Connection conn = (Connection) ds.getConnection();
        return conn;
    }

}
ReportHibernate.java
public class ReportHibernate extends HttpServlet {

    private static final long serialVersionUID = -433379001619945275L;
    private Logger logger = Logger.getLogger("ReportHibernate");

    @SuppressWarnings("unchecked")
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse res)
            throws ServletException {
        try {

            PoolConnection pool = new PoolConnection();
            Connection con = pool.getConnection();
            JasperReport jasperReport = null;
            byte[] pdfRelatorio = null;
            String sep = File.separator;
            String pathJasper = getServletContext().getRealPath("/content/reports/") + sep;
            Map parametros = new HashMap();
            jasperReport = (JasperReport) JRLoader.loadObject(
                pathJasper + "relatorioHibernate.jasper");
            pdfRelatorio = JasperRunManager.runReportToPdf(jasperReport, parametros, con);

            logger.info("CaminhoJasper: " + pathJasper);
            logger.info("JasperReport : " + jasperReport);
            logger.info("Parametros   : " + parametros);
            logger.info("Pdf          : " + pdfRelatorio);

            //Parametros para nao fazer cache e o que será exibido..
            res.setContentType("application/pdf");
            res.setHeader("Cache-Control", "no-store");
            res.setHeader("Pragma", "no-cache");
            res.setDateHeader("Expires", 0);

            //Envia para o navegador o pdf..
            ServletOutputStream servletOutputStream = res.getOutputStream();
            servletOutputStream.write(pdfRelatorio);
            servletOutputStream.flush();
            servletOutputStream.close();
        } catch (Exception ex) {
            Logger.getLogger(ReportHibernate.class.getName()).error(ex);
        }

    }

}

estou tento essa mensagem de erro:

11:30:07,687ERROR ReportHibernate:65 - javax.naming.NameNotFoundException: Name jdbc is not bound in this Context

e entao, o que mais preciso fazer para funcionar? estou usando o tomcat 6.0 com o banco mysql 5.0

3 Respostas

ze_kiefa

Você não configurou o datasource (pool de conexões) no Tomcat. Verifique mais detalhes aqui.

rollei

eu mudei o context.xml dentro do conf do tomcat ficou assim:

<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- The contents of this file will be loaded for each web application -->
<Context>

    <!-- Default set of monitored resources -->
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
	
    <!-- Uncomment this to disable session persistence across Tomcat restarts -->
    <!--
    <Manager pathname="" />
    -->

    <!-- Uncomment this to enable Comet connection tacking (provides events
         on session expiration as well as webapp lifecycle) -->
    <!--
    <Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
    -->

</Context>

<Context path="/hibernate"
         docBase="hibernate"
         debug="5"
         reloadable="true"
         crossContext="true">
    <Resource name="jdbc/hibernate"
              auth="Container"
              type="javax.sql.DataSource"
              maxActive="100"
              maxIdle="30"
              maxWait="300"
              username="root"
              password="senha"
              driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/hibernate"/>
</Context>

continua dando o mesmo erro

tentei mudar tambem o context.xml que ta dentro do META-INF da pasta web da aplicacao e continuo dando o mesmo erro, jah tentei reiniciar o tomcat e nada. to usando o usuario root do mysql ... alguma ideia do que possa ser?

rollei

alguem sabe me dizer o que falta eu fazer?

jah mudei o arquivo context.xml do tomcat, reinicei depois, mudei o web.xml da aplicacao. precisa fazer mais o que?

Criado 24 de maio de 2008
Ultima resposta 26 de mai. de 2008
Respostas 3
Participantes 2