How to Pass Parameters in Jasperreports

Asked

Viewed 1,768 times

0

Hello Guys good afternoon I’m having a doubt that is killing me. I have a project that has to print out a report that contains two lists and two tables. My problem is this, I have no intention of how Jasper interprets the data that is passed to him, because of the following:

In my report the first time I did, in Jasper studio I created the report with a fixed bank there everything worked perfectly, and then I passed this report to java, when I was running the code the report was generated with the database that was created in Jasper studio and not with the data passed by java.

Then I changed the report and there were more doubts, why I switched to the use of parameters and created the lists and tables without database, but the report does not even appear, even if I pass the parameters through java. My doubt is how Jasper interprets this data that I am passing, like, in my code I pass the connection of the database that I am using, it is really necessary to pass it since I pass the information by parameter?

Another question, searching the internet I noticed that I can put parameters in the sqls of the dataset I create in Jasper studio, as I can pass this parameters via java?

Below follows the codes I have made so far:

Class Generating the Report:

private Connection conexao;

public GeradorRelatorio(Connection conexao) {
    this.conexao = conexao;
}

public void geraPdf(String jrxml, 
    Map<String, Object> parametros, OutputStream saida) {

    try {
        // compila jrxml em memoria
        JasperReport jasper = JasperCompileManager.compileReport(jrxml);

        // preenche relatorio
        JasperPrint print = JasperFillManager.fillReport(jasper, parametros, this.conexao);

        // exporta para pdf
        JRExporter exporter = new JRPdfExporter();
        exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
        exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, saida);

        exporter.exportReport();

    } catch (Exception e) {
        e.printStackTrace();
    }
}   

Class passing the Parameters:

@WebServlet("/RelatorioMensalController")
public class RelatorioMensalController extends HttpServlet {
private static final long serialVersionUID = 1L;

private Conexao conexao;
private ParametrosRelatorio pr = new ParametrosRelatorio();

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    int idUsuario = Integer.parseInt(request.getParameter("idUsuario"));
    System.out.println(idUsuario);
    // acha jrxml dentro da aplicação
    ServletContext contexto = request.getServletContext();
    String jrxml = contexto.getRealPath("relatorio/exemplo.jrxml");

    // prepara parâmetros
    Map<String, Object> parametros = new HashMap<>();

    List<Conta> listaConta = pr.buscarContaUsuario(idUsuario);
    for (Conta conta : listaConta) {
        parametros.put("nomeConta", conta.getNome());
        parametros.put("saldo", conta.getSaldo());
        List<Debito> listaDebito = pr.buscarDebitosContasMesAtual(idUsuario, conta.getId());
        for (Debito debito : listaDebito) {
            parametros.put("descricaoDebitoConta", debito.getDescricao());
            parametros.put("valorDebitoConta", debito.getValor());
            parametros.put("dataDebitoConta", debito.getData());
        }
    }

    List<CartaoDeCredito> listaCartao = pr.buscarCartaoUsuario(idUsuario);
    for (CartaoDeCredito cartaoDeCredito : listaCartao) {
        parametros.put("nomeCartao", cartaoDeCredito.getNome());
        parametros.put("limite", cartaoDeCredito.getLimite());
        parametros.put("valorTotal", cartaoDeCredito.getValorTotal());
        parametros.put("vencimento", cartaoDeCredito.getVencimento());
        List<Debito> listaDebitoCartao = pr.buscarDebitosCartaoMesAtual(idUsuario, cartaoDeCredito.getId());
        for (Debito debito : listaDebitoCartao) {
            parametros.put("descricaoDebitoCartao", debito.getDescricao());
            parametros.put("valorDebitoCartao", debito.getValor());
            parametros.put("dataDebitoCartao", debito.getData());
        }
    }

    List<Object> listaCategoriaCartao = pr.buscarCategoriaCartaoMesAtual(idUsuario);
    for (Object object : listaCategoriaCartao) {
        if (object.getClass().equals(String.class)) {
            parametros.put("nomeCategoriaCartao", object);
            System.out.println(object);
        } else {
            parametros.put("quantidadeCartao", object);
        }
    }

    List<Object> listaCategoriaConta = pr.buscarCategoriaContaMesAtual(idUsuario);
    for (Object object : listaCategoriaConta) {
        if (object.getClass().equals(String.class)) {
            parametros.put("nomeCategoriaConta", object);
        } else {
            parametros.put("quantidadeConta", object);
        }
    }

    // abre conexão com o banco
    conexao = Conexao.getConexao();

    // gera relatório
    GeradorRelatorio gerador = new GeradorRelatorio(conexao.getConnection());
    gerador.geraPdf(jrxml, parametros, response.getOutputStream());

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    doGet(request, response);
}

I hope you can help me, I’ve never worked with Jasper Reports before so I’m really confused, I don’t know how it works.

Thank you from everyone.

  • If you need more information just ask

2 answers

1


First on the database connection.

Because Voce has to pass a connection in this case, when Voce is creating a relay usually creates according to the database information it wants to show, so when creating a report on tools like Jasperstudio you create a connection to do the tests with the actual data.

Then when you will generate the Voce report you need to send the connection to Jasper to know where you will get this data.

Actually Jasper works as follows, usually a report is created in a software like Jasperstudio. Inside it Voce has several options to assemble your report like adding fixed texts or images and so on as you wish and inside it there is also an option parameter.

inserir a descrição da imagem aqui

You create a parameter that can be used as Voce even said in Querys SQL and to set these parameter values is passed the Hashmap with the parameters as Voce is already doing.

For example, let’s say you created a parameter called "ID", to assign the value to it in its hashMap Voce arrow the value as follows.

When your report is generated it will use this value passed in your report.

parametros.put("ID","VALOR")

If I have any doubt here there is good example: report example

0

Thank you for the explanation, I’ve been researching since I asked the question here and along with your explanation I understood what I was doing wrong. But I still haven’t solved my problem. I’ll try to explain it better. I have a personal financial management system, and I want to provide a report that contains the user’s accounts and cards as well as the debts related to them, as well as two graphs with the categories in which the user spent the most.

The strategy I used to create the report was to put the list element to list the accounts and cards and within it I put a table with the debts. In the element datasets I put querys with parameter only that I can’t pass the data to these parameters. I don’t know if I’m using the right strategy or not, because I’ve never used Jasper before, so I’m very confused on how to put this information in the report.

If you have any suggestions on how to better organize or assemble the report I would appreciate it very much.

  • Report Code Repository: https://github.com/JessPergentino/reporterio.git

Browser other questions tagged

You are not signed in. Login or sign up in order to post.