🚀 Cómo mostrar reportes Jasper en Spring Boot MVC con Thymeleaf (Paso a paso)

 Si ya trabajas con Spring Boot y quieres integrar reportes profesionales con JasperReports, esta guía te mostrará cómo hacerlo de forma sencilla usando Thymeleaf.


📌 Requisitos previos

Antes de comenzar, asegúrate de tener:

  • Proyecto Spring Boot (MVC)

  • Archivo .jasper ya compilado (desde JasperSoft Studio)

  • Base de datos configurada

  • Dependencias básicas de Spring Web y Thymeleaf


📦 1. Agregar dependencias

En tu pom.xml, agrega JasperReports:

<dependency>
    <groupId>net.sf.jasperreports</groupId>
    <artifactId>jasperreports</artifactId>
    <version>6.20.0</version>
</dependency>

Si usas MySQL o SQL Server, asegúrate de tener su driver.


📁 2. Ubicar el archivo .jasper

Coloca tu archivo .jasper dentro del proyecto, por ejemplo en la ruta:

src/main/resources/reports/mi_reporte.jasper

⚙️ 3. Crear clase de servicio para generar el reporte

import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.util.JRLoader;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

@Service
public class ReporteService {

    private final DataSource dataSource;

    public ReporteService(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public byte[] generarReporte() {
        try (Connection conn = dataSource.getConnection()) {

            InputStream reporteStream = getClass()
                    .getResourceAsStream("/reports/mi_reporte.jasper");

            JasperReport reporte = (JasperReport) JRLoader.loadObject(reporteStream);

            Map<String, Object> parametros = new HashMap<>(); //si utilizas parametros
            // Ejemplo: parametros.put("id", 1);

            JasperPrint print = JasperFillManager.fillReport(reporte, parametros, conn);

            return JasperExportManager.exportReportToPdf(print);

        } catch (Exception e) {
            throw new RuntimeException("Error al generar reporte", e);
        }
    }
}

🌐 4. Crear controlador

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class ReporteController {

    private final ReporteService reporteService;

    public ReporteController(ReporteService reporteService) {
        this.reporteService = reporteService;
    }

    @GetMapping("/reporte/pdf")
    public ResponseEntity<byte[]> verReportePDF() {

        byte[] pdf = reporteService.generarReporte();

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=reporte.pdf")
                .contentType(MediaType.APPLICATION_PDF)
                .body(pdf);
    }

    @GetMapping("/reporte")
    public String vistaReporte() {
        return "reporte";
    }
}

🖥️ 5. Crear vista con Thymeleaf

Archivo: src/main/resources/templates/reportes/reporte.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Reporte Jasper</title>
</head>
<body>

<h2>Ver Reporte</h2>

<a th:href="@{/reporte/pdf}" target="_blank">
    Ver Reporte PDF
</a>

</body>
</html>

▶️ 6. Ejecutar y probar

  1. Ejecuta tu aplicación Spring Boot

  2. Ve a:

http://localhost:8080/reporte
  1. Haz clic en el enlace → se abrirá el PDF generado


🧠 Tips importantes

  • Si usas parámetros en tu reporte .jasper, agrégalos en el Map<String, Object>

  • Puedes exportar a otros formatos:

    • Excel (JRXlsxExporter)

    • HTML

  • Usa inline para mostrar en navegador o attachment para descargar


⚡ Ejemplo con parámetros

parametros.put("fecha_inicio", "2026-01-01");
parametros.put("fecha_fin", "2026-12-31");

🧩 Estructura recomendada del proyecto

controller/
    ReporteController.java
service/
    ReporteService.java
resources/
    reports/
        mi_reporte.jasper
templates/
    reporte.html

🎯 Conclusión

Integrar JasperReports con Spring Boot es más fácil de lo que parece. Con esta estructura:

  • Separas lógica (Service)

  • Controlas endpoints (Controller)

  • Mantienes UI simple con Thymeleaf


Comentarios

Entradas populares de este blog

Aprende a Armar tu PC con el Simulador de Cisco 🖥️ Guía Paso a Paso

¿Qué es XAMPP y cómo descargarlo e instalarlo en Windows?

🗄️ Cómo Instalar y usar SQLite en Windows [Guía Paso a Paso]