Para crear el proyecto
1. File
2. New
3. Maven Project
4. Create a simple project
mvn clean install -Dmaven.test.skip=true mvn -o clean install -Dmaven.test.skip=true
mvn clean -o install mvn -o eclipse:clean mvn -o eclipse:eclipse
mvn clean install mvn eclipse:clean mvn eclipse:eclipse
The dependencies are:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring</artifactId> <version>2.5.6</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>2.5.6</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>2.5.6</version> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.10</version> </dependency>
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> <version>3.1.3</version> </dependency>
<dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.1.2</version> </dependency>
<dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency>
<dependency> <groupId>org.slf4j13</groupId> <artifactId>slf4j-log4j13</artifactId> <version>1.0-beta9</version> </dependency>
For the following error:
[INFO] Unable to find resource 'org.slf4j13:slf4j-log4j13:jar:1.0-beta9' in repository central (http://repo1.maven.org/maven2) [INFO] ------------------------------------------------------------------------ [ERROR] BUILD ERROR [INFO] ------------------------------------------------------------------------ [INFO] Failed to resolve artifact.
Run the next snippet. Before you need download the slf4j-1.3.0.zip file:
mvn install:install-file -DgroupId=org.slf4j13 -DartifactId=slf4j-log4j13 -Dversion=1.0-beta9 -Dpackaging=jar -Dfile=C:/"Documents and Settings"/OfficegrafF/slf4j-1.3.0.zip
For the following error:
[INFO] Unable to find resource 'javax.transaction:jta:jar:1.0.1B' in repository central (http://repo1.maven.org/maven2) [INFO] ------------------------------------------------------------------------ [ERROR] BUILD ERROR [INFO] ------------------------------------------------------------------------ [INFO] Failed to resolve artifact.
Try downloading the jta-1_0_1B-classes.zip file and execute the command:
mvn install:install-file -DgroupId=javax.transaction -DartifactId=jta -Dversion=1.0.1B -Dpackaging=jar -Dfile=C:/"Documents and Settings"/ronald/jta-1_0_1B-classes.zip
/* * Asegurar que existe el archivo jasper */ ServletContext sc = getServletConfig().getServletContext(); String vjrxmlPath = "/WEB-INF/classes/reports/detObjMet.jrxml"; String vjasperPath = "/WEB-INF/classes/reports/detObjMet.jasper"; InputStream is = sc.getResourceAsStream(vjasperPath); if (is == null) { String rp = sc.getRealPath(vjrxmlPath); JasperCompileManager.compileReportToFile(rp); is = sc.getResourceAsStream(vjasperPath); } /* * Configuracion del datasource */ Connection con; Statement stm; ResultSet rs; String jdbcDriver = "com.mysql.jdbc.Driver"; Class.forName(jdbcDriver); String jdbcUrl = "jdbc:mysql://localhost:3306/course?user=root"; con = DriverManager.getConnection(jdbcUrl); String query = "SELECT COURSE_ID, NAME, COURSE FROM COURSE"; stm = con.createStatement(); rs = stm.executeQuery(query); JRResultSetDataSource jrds = new JRResultSetDataSource(rs); /* * Configuracion de los parametros de posicionamiento de imagenes */ String vlogoPath = "/images/logo_home_2.jpg"; String logoPath = sc.getRealPath(vlogoPath); String vukasPath = "/images/ukas.gif"; String ukasPath = sc.getRealPath(vukasPath); String vsgsPath = "/images/sgs.gif"; String sgsPath = sc.getRealPath(vsgsPath); HashMap<String, String> params = new HashMap<String, String>(); params.put("logoPath", logoPath); params.put("ukasPath", ukasPath); params.put("sgsPath", sgsPath); /* * Creamos el objeto jasper print */ String jasperPath = sc.getRealPath(vjasperPath); JasperPrint jprint = JasperFillManager.fillReport(jasperPath, params, jrds);
El punto de partida sera el proyecto creado con soporte para WTP usando Maven y Eclipse.
Editar el archivo pom.xml para agregar las dependencias de JasperReports, le daremos soporte para mostrar los reportes en PDF:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>jrwebapp</groupId> <artifactId>jrwebapp</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>jrwebapp Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.2</version> <scope>provided</scope> <optional>true</optional> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.7.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>[2.1,)</version> <scope>compile</scope> </dependency> <dependency> <groupId>commons-digester</groupId> <artifactId>commons-digester</artifactId> <version>[1.7,)</version> <scope>compile</scope> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>[1.0,)</version> <scope>compile</scope> </dependency> <dependency> <groupId>eclipse</groupId> <artifactId>jdtcore</artifactId> <version>[3.1.0,)</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.lowagie</groupId> <artifactId>itext</artifactId> <version>2.1.0</version> <scope>compile</scope> </dependency> <dependency> <groupId>jasperreports</groupId> <artifactId>jasperreports</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>jrwebapp</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.0.2</version> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <version>2.4</version> <configuration> <downloadSources>false</downloadSources> <wtpversion>1.5</wtpversion> </configuration> </plugin> </plugins> </pluginManagement> </build> </project>
Luegon desde el directorio donde se encuentra el archivo pom.xml del proyecto ingresar el comando:
mvn clean install
Cuando termine de actualizar el repositorio ingresar el comando:
mvn eclipse:clean eclipse:eclipse
Ahora le agregamos un servlet usando Eclipse:
Editamos el archivo JRServlet.java de modo que quede así:
package com.rab.ctrl;
import java.io.IOException; import java.io.PrintWriter;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/** * Servlet implementation class JRServlet */ public class JRServlet extends HttpServlet { private static final long serialVersionUID = 1L;
/** * @see HttpServlet#HttpServlet() */ public JRServlet() { super(); // TODO Auto-generated constructor stub }
/** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse * response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>JasperReports!</title>" + "</head><body>Hello Servlet!</body></html>"); out.close(); }
/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub }
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub }
}
El archivo web.xml debe quedar así:
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app> <display-name>JasperReports Web Application</display-name> <servlet> <servlet-name>JRServlet</servlet-name> <display-name>JRServlet</display-name> <description></description> <servlet-class> com.rab.ctrl.JRServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>JRServlet</servlet-name> <url-pattern>/JRServlet</url-pattern> </servlet-mapping> </web-app>
Finalmente editamos el archivo index.jsp el cual quedaría asi:
<html> <body> <h2>Hello World!</h2> <a href="/jrwebapp/JRServlet">/JRServlet</a> </body> </html>
Desplegamos en el servidor y el resultado sera el siguiente:
Ahora modificamos el método service de JRServlet así:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletContext sc = getServletConfig().getServletContext(); String jrxmlPath = "/WEB-INF/classes/reports/PrimerReport.jrxml"; String jasperPath = "/WEB-INF/classes/reports/PrimerReport.jasper"; InputStream is = sc.getResourceAsStream(jasperPath); if (is == null) { String rp = sc.getRealPath(jrxmlPath); JasperCompileManager.compileReportToFile(rp); is = sc.getResourceAsStream(jasperPath); } ServletOutputStream sos = response.getOutputStream(); JasperRunManager.runReportToPdfStream(is, sos, new HashMap(), new JREmptyDataSource()); response.setContentType("application/pdf"); sos.flush(); sos.close(); } catch (JRException e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); response.setContentType("text/plain"); response.getOutputStream().print(sw.toString()); } }
Tenemos la siguiente estructura de aplicación web, en el directorio jrwebapp creamos la carpeta reports
En la carpeta reports creamos un archivo PrimerReport.jrxml con el siguiente contenido:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE jasperReport PUBLIC "-//JasperReports//DTD Report Design//EN" "http://jasperreports.sourceforge.net/dtds/jasperreport.dtd"> <jasperReport name="PrimerReport"> <detail> <band height="20"> <staticText> <reportElement x="20" y="0" width="200" height="20" /> <text><![CDATA[El primer paso con JasperReports.]]></text> </staticText> </band> </detail> </jasperReport>
Finalmente, ejecutamos el proyecto y el resultado sería el siguiente:
Ir al directorio C:\java\workspace e ingresar el siguiente comando:
mvn archetype:create -DgroupId=jrwebapp -DartifactId=jrwebapp -DarchetypeArtifactId=maven-archetype-webapp
El resultado es la siguiente estructura:
Ir al directorio C:\java\workspace\jrwebapp es donde se encuentra el archivo pom.xml, desde alli ingresar el siguiente comando:
mvn eclipse:clean eclipse:eclipse
Abrir eclipse e importar el proyecto
Este es el resultado final:
Para dar a nuestro proyecto soporte WTP editar el archivo pom.xml de modo que quede así:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>jrwebapp</groupId> <artifactId>jrwebapp</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>jrwebapp Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.2</version> <scope>provided</scope> <optional>true</optional> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <build> <finalName>jrwebapp</finalName> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.0.2</version> <configuration> <source>1.5</source> <target>1.5</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-eclipse-plugin</artifactId> <version>2.4</version> <configuration> <downloadSources>false</downloadSources> <wtpversion>1.5</wtpversion> </configuration> </plugin> </plugins> </pluginManagement> </build> </project>
En la consola ingresar los comandos:
mvn clean install
Y luego ingresar los comandos:
mvn eclipse:clean eclipse:eclipse
El resultado seria:
Al ejecutar el proyecto el resultado final sería:
Descomprimir el archivo binario apache-maven-2.2.0-bin.zip en el directorio de trabajo, por ejemplo en: C:\java.
Crear la variable de entorno M2_HOME con el valor correspondiente al directorio donde se instalo Maven.
M2_HOME=C:\java\apache-maven-2.2.0
Luego se debe editar la variable de entorno PATH.
PATH=%PATH%;%M2_HOME%\bin
Configurar la variable de sistema:
JAVA_HOME=C:\java\jdk1.6.0_16
Abrir una consola de comandos y ejecutar el siguiente comando para verificar la configuración:
mvn --version
Abrir el archivo settings.xml de la carpeta C:\java\apache-maven-2.2.0\conf y configurar el repositorio:
<localRepository>C:/java/.m2/repository</localRepository>
Para crear un proyecto con Maven ir a un directorio, ejemplo C:\java\tutorials e ingresar el siguiente comando:
mvn archetype:create -DgroupId=com.report.proy -DartifactId=reportproy
El resultado es el siguiente proyecto:
Crearemos un proyecto basico usando el plugin que integra Maven con Eclipse.
Primero instalar el plugin.
Seleccionamos un sitio desde el cual descargar el plugin haciendo clic en el link Available Software Sites.
Clic en Add e insertamos la URL del host donde se almacena el plugin para Maven.
Luego de que se instale el plugin reiniciamos eclipse y desde el menu Window > Preferences configuramos las opciones de entorno de ejecución, asegurarse que esta usando el JDK y no el JRE. (Puedes ver como se instala Java y como se configura el entorno de ejecución desde este link).
Abrir el archivo eclipse.ini y configuramos la maquina virtual a la que esta apuntando eclipse, cerrar y guardar los cambios.
Para asegurarnos de que los cambios surtan efectos iniciamos eclipse desde la consola con la opcion clean.
Seleccionar el menu New>Other.
En el asistente seleccionamos Maven Project y clic en Next.
Seleccionar la plantilla quickstart y clic en Next.
LLenar los campos correspondientes.
Clic derecho y seleccionar ejecutar como una aplicacion Java.
Seleccionar la aplicación correspondiente.
Es todo por el momento.