Despues de haber configurado Netbeans debemos:
Configurar el Proyecto
En el IDE, enla pestaña Proyects damos clic derecho sobre nuestra Aplicacion Web "Proyecto" y selecionamos Propiertes, nos aparecera la sgte ventana:
4. Configurar el servidor de Aplicaciones (Glassfish).
En el explorador de windows, nos vamos a la carpeta donde tenemos instalado nuestro servidor de aplicaciones, y luego hasta el subdirectorio de nuestro dominio config, en mi caso "C:\Archivos de programa\glassfish-v2ur2\domains\domain1\config", y editamos el archivo server.policy...
Agregamos el siguiente segmento de Codigo:
// Librerias Jaspergrant codeBase "file:/C:/aplicaci/Syslex/build/web/-"{
permission java.util.PropertyPermission "*", "read,write";
permission java.lang.RuntimePermission "createClassLoader";
permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
permission java.lang.RuntimePermission "accessDeclaredMembers";
permission java.lang.RuntimePermission "getProtectionDomain";
};
grant {
permission java.lang.RuntimePermission "createClassLoader";
Ojo, deben reemplazar la ruta de color rojo por la de su proyecto.!
Ahora, nos regresamos al proyecto y agregamos una nueva carpeta llamada reportes en la ruta scr
En el proyecto nos vamos a Web Pages > WEB-INF y abrimos el archivo web.xml ...
...en la Ficha Servlets, damos clic en el boton ubicado en la esquina superior derecha Add Servlet Element
Escribimos lo sgte:
- Servlet Name: ImageServlet
- ServletClass: net.sf.jasperreports.j2ee.servlets.ImageServlet
- URL Pattern(s): /images
y damos OK
En el proyecto creamos una nueva carpeta con el nombre images, en la ruta web\resources
En el IDE, nos vamos a la Pestaña Files selecionamos nuestro proyecto y abrimos el archivo build.xml
y agregamos antes de la etiqueta </project> el sgte codigo:
<property name="jrc.home"
value="c:\descargas\java\jasperreports-1.3.3"/>
<path id="jrc.classpath">
<fileset dir="${jrc.home}/dist"
includes="*.jar"/>
<fileset dir="${jrc.home}/lib"
includes="*.jar"/>
</path>
<taskdef name="jrc"
classname="net.sf.jasperreports.ant.JRAntCompileTask">
<;classpath refid="jrc.classpath"/>
</taskdef>
<target name="-post-compile"
description="Compile all Jasper Reports Definitions">
<mkdir dir="${build.web.dir}/WEB-INF/reportes"/>
<jrc srcdir="src/reportes"
destdir="${build.web.dir}/WEB-INF/reportes">
<classpath
refid="jrc.classpath"/>
<include
name="*.jrxml"/>
</jrc>
<delete>
<fileset dir="${build.web.dir}/WEB-INF/classes"
includes="*.jrxml"/>
</delete>
</target>
Ojo, deben reemplazar la ruta de color rojo por la del proyecto jasper-reports-1.3.3 !
Por último, abrir el ApplicationBean1.java y agregar el siguiente código al final
/**
* <p>Prefix to the resource name for compiled reports.</p>
*/
private static final String PREFIX = "/WEB-INF/reportes/";
/**
* <p>Suffix to the resource name for compiled reports.</p>
*/
private static final String SUFFIX = ".jasper";
/**
* <p>Valid content types for reports that we can produce.</p>
*/
private static final String[] VALID_TYPES = {"text/html", // Standard HTML representation
"application/pdf", // Adobe Portable Document Format
"application/rtf" //Microsoft Word RTF
};
/**
* <p>Generate the specified report, in the specified output
* format, based on the specified data.</p>
*
* @param name Report name to be rendered
* @param type Content type of the requested report ("application/pdf"
* or "text/html")
* @param data <code>ResultSet</code> containing the data to report
*
* @exception IllegalArgumentException if the specified
* content type is not recognized
* @exception IllegalArgumentException if no compiled report definition
* for the specified name can be found
*/
public void jasperReport(String name, String type) {
jasperReport(name, type, new HashMap());
}
//Editado by elcapi
public void jasperReport(String name, String type, ResultSet data) {
jasperReport(name, type, new HashMap());
}
/**
* <p>Generate the specified report, in the specified output
* format, based on the specified data.</p>
*
* @param name Report name to be rendered
* @param type Content type of the requested report ("application/pdf"
* or "text/html")
* @param data <code>ResultSet</code> containing the data to report
* @param params <code>Map</code> of additional report parameters
*
* @exception IllegalArgumentException if the specified
* content type is not recognized
* @exception IllegalArgumentException if no compiled report definition
* for the specified name can be found
*/
public void jasperReport(String name, String type, ResultSet data, Map params) {
if (!isReporte(type)) {
return;
}
ExternalContext econtext = getExternalContext();
// Fill the requested report with the specified data
JRResultSetDataSource ds = new JRResultSetDataSource(data);
JasperPrint jasperPrint = nextPrint(this.compilarReporte(econtext, name), params, null, ds, 1);
generarReporte(econtext, type, jasperPrint);
}
//Reportes que no necesitan ResulSet...
public void jasperReport(String name, String type, Map params) {
if (!isReporte(type)) {
return;
}
ExternalContext econtext = getExternalContext();
Connection conx = this.getConexion();
JasperPrint jasperPrint = nextPrint(this.compilarReporte(econtext, name), params, conx, null, 0);
// Configure the exporter to be used, along with the custom
// parameters specific to the exporter type
generarReporte(econtext, type, jasperPrint);
}
private Boolean isReporte(String type) {
// Validate that we recognize the report type
// before potentially wasting time filling the
// report with data
boolean found = false;
for (int i = 0; i < VALID_TYPES.length; i++) {
if (VALID_TYPES[i].equals(type)) {
found = true;
break;
}
}
if (!found) {
throw new IllegalArgumentException("Invalid report type '" + type + "' requested");
}
return found;
}
private InputStream compilarReporte(ExternalContext econtext, String name) {
InputStream stream = econtext.getResourceAsStream(PREFIX + name + SUFFIX);
if (stream == null) {
throw new IllegalArgumentException("Unknown report name '" + name + "' requested");
}
return stream;
}
private Connection getConexion() {
Context ctx;
Connection conx;
try {
ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/Name_Conexion");
conx = dataSource.getConnection();
} catch (Exception e) {
throw new FacesException(e);
}
return conx;
}
private JasperPrint nextPrint(InputStream stream, Map params, Connection conx, JRResultSetDataSource ds, int opcion) {
JasperPrint jasperPrint = null;
try {
switch (opcion) {
case 0:
jasperPrint = JasperFillManager.fillReport(stream, params, conx);
break;
case 1:
jasperPrint = JasperFillManager.fillReport(stream, params, ds);
break;
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
} finally {
try {
stream.close();
} catch (IOException e) {
log(e.getMessage());
}
}
return jasperPrint;
}
private void generarReporte(ExternalContext econtext, String type, JasperPrint jasperPrint) {
JRExporter exporter = null;
HttpServletResponse response = (HttpServletResponse) econtext.getResponse();
FacesContext fcontext = FacesContext.getCurrentInstance();
try {
response.setContentType(type);
if ("application/pdf".equals(type)) {
exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
} else if ("text/html".equals(type)) {
exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_WRITER, response.getWriter());
// Make images available for the HTML output
HttpServletRequest request = (HttpServletRequest) fcontext.getExternalContext().getRequest();
request.getSession().setAttribute(ImageServlet.DEFAULT_JASPER_PRINT_SESSION_ATTRIBUTE, jasperPrint);
exporter.setParameter(JRHtmlExporterParameter.IMAGES_MAP, new HashMap());
// The following statement requires mapping /image
// to the imageServlet in the web.xml.
//
// This servlet serves up images including the px
// images for spacing.
//
// Serve up the images directly so we
// don't incur the extra overhead associated with
// with a JSF request for a non-JSF entity.
exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, request.getContextPath() + "/image?image=");
} else if ("application/rtf".equals(type)) {
exporter = new JRRtfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, response.getOutputStream());
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}
// Enough with the preliminaries ... export the report already
try {
exporter.exportReport();
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new FacesException(e);
}
// Tell JavaServer Faces that no output is required
fcontext.responseComplete();
}