1. java
  2. android
  3. c#
  4. .net
  5. javascript
  6. php
  7. jquery
  8. html
  9. sql

Relatório com JSF WEB IReport

Pessoal, estudei alguns POST idênticos e não consegui encontrar a solução da Exception que apareceu, também não tenho certeza que chamei a lista de forma correta, peço por gentileza ajuda aos "universitários".Lembrando que realizei os testes com o relatório em branco e com alguns campos e rodou tranquilamente.

 public void gerarRelatorio() {
         ItemDAO itemDAO = new ItemDAO();
         listaItens = itemDAO.listar();
                 ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
            ServletContext context = (ServletContext) externalContext.getContext();
            String arquivo = context.getRealPath("WEB-INF/relatorios/itemNF.jasper");

            JRDataSource jrds = new JRBeanCollectionDataSource(listaItens);

            gerarRelatorioWeb(jrds, null, arquivo);
        }

        private void gerarRelatorioWeb(JRDataSource jrds, Map<String, Object> parametros, String arquivo) {
            ServletOutputStream servletOutputStream = null;
            FacesContext context = FacesContext.getCurrentInstance();
            HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();

            try {
                servletOutputStream = response.getOutputStream();
                JasperRunManager.runReportToPdfStream(new FileInputStream(new File(arquivo)), response.getOutputStream(), parametros, jrds);
                response.setContentType("application/pdf");
                servletOutputStream.flush();
                servletOutputStream.close();
                context.renderResponse();
                context.responseComplete();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

.xhtml

<p:commandButton value="Ver relatorio" actionListener="#{vendaBean.gerarRelatorio}" onclick="this.form.target='_blank'" />

Exception

GRAVE: Error Rendering View[/pages/vendaPesquisa.xhtml]
java.lang.IllegalStateException: getOutputStream() has already been called for this response
    at org.apache.catalina.connector.Response.getWriter(Response.java:578)
    at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:212)
    at com.sun.faces.context.ExternalContextImpl.getResponseOutputWriter(ExternalContextImpl.java:851)
    at javax.faces.context.ExternalContextWrapper.getResponseOutputWriter(ExternalContextWrapper.java:785)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.createResponseWriter(FaceletViewHandlingStrategy.java:1208)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:405)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:134)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:337)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:120)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

Nov 24, 2015 4:17:53 PM org.apache.catalina.core.StandardWrapperValve invoke
GRAVE: Servlet.service() for servlet [Faces Servlet] in context with path [/CeratotheriumSimum] threw exception
java.lang.IllegalStateException: getOutputStream() has already been called for this response
    at org.apache.catalina.connector.Response.getWriter(Response.java:578)
    at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:212)
    at com.sun.faces.context.ExternalContextImpl.getResponseOutputWriter(ExternalContextImpl.java:851)
    at com.sun.faces.context.PartialViewContextImpl.createPartialResponseWriter(PartialViewContextImpl.java:504)
    at com.sun.faces.context.PartialViewContextImpl.access$300(PartialViewContextImpl.java:79)
    at com.sun.faces.context.PartialViewContextImpl$DelayedInitPartialResponseWriter.getWrapped(PartialViewContextImpl.java:642)
    at javax.faces.context.PartialResponseWriter.startDocument(PartialResponseWriter.java:120)
    at org.primefaces.context.PrimePartialResponseWriter.startDocument(PrimePartialResponseWriter.java:146)
    at org.omnifaces.context.OmniPartialViewContext$OmniPartialResponseWriter.startDocument(OmniPartialViewContext.java:277)
    at com.sun.faces.context.AjaxExceptionHandlerImpl.handlePartialResponseError(AjaxExceptionHandlerImpl.java:202)
    at com.sun.faces.context.AjaxExceptionHandlerImpl.handle(AjaxExceptionHandlerImpl.java:127)
    at javax.faces.context.ExceptionHandlerWrapper.handle(ExceptionHandlerWrapper.java:100)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:119)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:219)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:659)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)

Erro após Modificar o código como descrito abaixo.

com.sun.faces.lifecycle.InvokeApplicationPhase execute
ADVERTÊNCIA: java.lang.NullPointerException
javax.el.ELException: java.lang.NullPointerException
    at org.apache.el.parser.AstValue.invoke(AstValue.java:260)
    at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:267)
    at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:149)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:814)
    at javax.faces.component.UICommand.broadcast(UICommand.java:300)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:658)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NullPointerException
    at java.io.File.<init>(Unknown Source)
    at net.sf.jasperreports.engine.JasperFillManager.fill(JasperFillManager.java:563)
    at net.sf.jasperreports.engine.JasperFillManager.fillReport(JasperFillManager.java:915)
    at br.pro.csimum.erp.bean.VendaBean.gerarRelatorioWeb(VendaBean.java:234)
    at br.pro.csimum.erp.bean.VendaBean.gerarRelatorio(VendaBean.java:230)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.el.parser.AstValue.invoke(AstValue.java:247)
    ... 32 more

Bean

@ManagedBean
@ViewScoped
public class ItensNFBean {
    private Item itemCadastro;
    private List<Item> listaItens;
    private List<Item> listaItensFiltrados;
    private String acao;
    private Long codigo;

    public Item getItemCadastro() {
        return itemCadastro;
    }

    public void setItemCadastro(Item itemCadastro) {
        this.itemCadastro = itemCadastro;
    }

    public List<Item> getListaItens() {
        return listaItens;
    }
    public void setListaItens(List<Item> listaItens) {
        this.listaItens = listaItens;
    }
    public List<Item> getListaItensFiltrados() {
        return listaItensFiltrados;
    }
    public void setListaItensFiltrados(List<Item> listaItensFiltrados) {
        this.listaItensFiltrados = listaItensFiltrados;
    }

    public Long getCodigo() {
        return codigo;
    }


    public void setCodigo(Long codigo) {
        this.codigo = codigo;
    }

    public String getAcao() {
        return acao;
    }

    public void setAcao(String acao) {
        this.acao = acao;
    }

    public void carregarPesquisa() {
        try {
            ItemDAO ItemDAO = new ItemDAO();
            listaItens = ItemDAO.listar();


        } catch (RuntimeException ex) {
            FacesUtil.adicionarMsgErro("Erro ao tentar listar os itens:"
                    + ex.getMessage());
        }
    }

    public void carregarCadastro() {
        try {

            if (codigo != null) {
                ItemDAO ItemDAO = new ItemDAO();
                itemCadastro = ItemDAO.buscarPorCodigo(codigo);

            } else {
                itemCadastro = new Item();

            }
        } catch (RuntimeException ex) {
            FacesUtil
                    .adicionarMsgErro("Erro ao tentar obter os dados dos Itens:"
                            + ex.getMessage());

        }
    }

    public void gerarRelatorio() throws JRException {
        ItemDAO ItemDAO = new ItemDAO();
        listaItens = ItemDAO.listar();
carregarCadastro();
        String arquivo = FacesContext.getCurrentInstance().getExternalContext().getRealPath("WEB-INF/relatorios/itemNF.jasper");
        JRBeanCollectionDataSource jrds = new JRBeanCollectionDataSource(listaItens);
        gerarRelatorioWeb(jrds, null, arquivo);
    }

     private void gerarRelatorioWeb(JRBeanCollectionDataSource jrds, Map<String, Object> parametros, String arquivo) throws JRException {
            JasperPrint relatorio = JasperFillManager.fillReport(arquivo, parametros, jrds);
            if (relatorio != null) {
                HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
                response.setContentType("application/pdf");
                response.addHeader("Content-disposition", "inline; filename=itemNF.pdf");
                try {
                    ServletOutputStream servletOutputStream = response.getOutputStream();
                    JasperExportManager.exportReportToPdfStream(relatorio, servletOutputStream);
                } catch (JRException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                FacesContext.getCurrentInstance().responseComplete();
            }
        }
}
  1. Você vai ver essas setas em qualquer página de pergunta. Com elas, você pode dizer se uma pergunta ou uma resposta foram relevantes ou não.
  2. Edite sua pergunta ou resposta caso queira alterar ou adicionar detalhes.
  3. Caso haja alguma dúvida sobre a pergunta, adicione um comentário. O espaço de respostas deve ser utilizado apenas para responder a pergunta.
  4. Se o autor da pergunta marcar uma resposta como solucionada, esta marca aparecerá.
  5. Clique aqui para mais detalhes sobre o funcionamento do GUJ!

1 resposta

Não é a resposta que estava procurando? Procure outras perguntas com as tags java hibernate mysql ireport web servlets jasperreports jsf primefaces ou faça a sua própria pergunta.