Fecha de creación del tutorial: 2003-07-17
TagLibs con Cuerpo
Vamos a mostrar en este tutorial como construir TAG que interactuen con su contenido y que tengan la capacidad de contener otras etiquetas
Vamos a utilizar NetBeans. Creamos un nuevo proyectos

Posteriormente lo convertimos en un WebModule y lo convertimos en un JSP.

Le asignamos un nombre.

Vamos a crear una nueva etiqueta que sea capaz de repetir una grupo de cadena de caracteres que tiene dentro... posteriormente ya lo complicaremos.
Insertamos la librería de TAGs

Le asignamos un nombre al grupo

Ahora craremos una nueva etiqueta que vamos a llamar repetir

Le asignamos los valores deseados

Le decimos que es un tag con cuerpo.

Ahora añadimos un atributo

Asignamos un nombre, tipo (int) y lo definimos como obligatorio.

Ahora creamos las clases en base a la especificación

El sistema nos indica que ha creado una nueva clase

El código generado posee unos comentario que debemos leer atentamente...
package roberto;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.IterationTag;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
/**
* Generated tag class.
*/
public class RepetirTag extends BodyTagSupport {
/** property declaration for tag attribute: numeroveces.
*
*/
private int numeroveces;
public RepetirTag() {
super();
}
////////////////////////////////////////////////////////////////
/// ///
/// User methods. ///
/// ///
/// Modify these methods to customize your tag handler. ///
/// ///
////////////////////////////////////////////////////////////////
//
// methods called from doStartTag()
//
/**
*
* Fill in this method to perform other operations from doStartTag().
*
*/
public void otherDoStartTagOperations() {
//
// TODO: code that performs other operations in doStartTag
// should be placed here.
// It will be called after initializing variables,
// finding the parent, setting IDREFs, etc, and
// before calling theBodyShouldBeEvaluated().
//
// For example, to print something out to the JSP, use the following:
//
// try {
// JspWriter out = pageContext.getOut();
// out.println("something");
// } catch (java.io.IOException ex) {
// // do something
// }
//
//
}
/**
*
* Fill in this method to determine if the tag body should be evaluated
* Called from doStartTag().
*
*/
public boolean theBodyShouldBeEvaluated() {
//
// TODO: code that determines whether the body should be
// evaluated should be placed here.
// Called from the doStartTag() method.
//
return true;
}
//
// methods called from doEndTag()
//
/**
*
* Fill in this method to perform other operations from doEndTag().
*
*/
public void otherDoEndTagOperations() {
//
// TODO: code that performs other operations in doEndTag
// should be placed here.
// It will be called after initializing variables,
// finding the parent, setting IDREFs, etc, and
// before calling shouldEvaluateRestOfPageAfterEndTag().
//
}
/**
*
* Fill in this method to determine if the rest of the JSP page
* should be generated after this tag is finished.
* Called from doEndTag().
*
*/
public boolean shouldEvaluateRestOfPageAfterEndTag() {
//
// TODO: code that determines whether the rest of the page
// should be evaluated after the tag is processed
// should be placed here.
// Called from the doEndTag() method.
//
return true;
}
////////////////////////////////////////////////////////////////
/// ///
/// Tag Handler interface methods.///
/// ///
/// Do not modify these methods; instead, modify the ///
/// methods that they call. ///
/// ///
////////////////////////////////////////////////////////////////
/** .
*
* This method is called when the JSP engine encounters the start tag,
* after the attributes are processed.
* Scripting variables (if any) have their values set here.
* @return EVAL_BODY_INCLUDE if the JSP engine should evaluate the tag body, otherwise return SKIP_BODY.
* This method is automatically generated. Do not modify this method.
* Instead, modify the methods that this method calls.
*
*
*/
public int doStartTag() throws JspException, JspException {
otherDoStartTagOperations();
if (theBodyShouldBeEvaluated()) {
return EVAL_BODY_BUFFERED;
} else {
return SKIP_BODY;
}
}
/** .
*
*
* This method is called after the JSP engine finished processing the tag.
* @return EVAL_PAGE if the JSP engine should continue evaluating the JSP page, otherwise return SKIP_PAGE.
* This method is automatically generated. Do not modify this method.
* Instead, modify the methods that this method calls.
*
*
*/
public int doEndTag() throws JspException, JspException {
otherDoEndTagOperations();
if (shouldEvaluateRestOfPageAfterEndTag()) {
return EVAL_PAGE;
} else {
return SKIP_PAGE;
}
}
public int getNumeroveces() {
return numeroveces;
}
public void setNumeroveces(int value) {
numeroveces = value;
}
/** .
* Fill in this method to process the body content of the tag.
* You only need to do this if the tag's BodyContent property
* is set to "JSP" or "tagdependent."
* If the tag's bodyContent is set to "empty," then this method
* will not be called.
*
*
*/
public void writeTagBodyContent(JspWriter out, BodyContent bodyContent) throws IOException {
//
// TODO: insert code to write html before writing the body content.
// e.g. out.println("" + getAttribute1() + "");
|
Ahora nuestro trabajo será rellenar el código de distintos métodos para conseguir nuestro objetivo.
La lógica es sencilla, se procesa el cuerpo de la página
public void writeTagBodyContent(JspWriter out, BodyContent bodyContent) throws IOException {
bodyContent.writeOut(out);
numeroveces--;
bodyContent.clearBody();
}
public boolean theBodyShouldBeEvaluatedAgain() {
if (this.numeroveces > 0)
return true;
return false;
}
|

El JSP lo podemos construir con esta forma
| <%@page contentType="text/html"%> <%@taglib uri="tagsroberto.tld" prefix="rc"%> <html> <head><title>JSP Page</title></head> <body> <rc:repetir numeroveces="4"> Esta cadena la repetiremos varias veces <br> </rc:repetir> </body> </html> |
El resultado sería el siguiente

Tag Anidado
Ahora vamos a crear una nueva etiqueta que se intertaría dentro de la actual, para simplemente mostrar el valor del contador.

Añadimos un tag simple sin cuerpo

Especificamos que queremos acceder al tag que la contiene .... en la variable repetirTagPadre


Modificamos el código automáticamente generado
package roberto;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTag;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.IterationTag;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
/**
* Generated tag class.
*/
public class ValorcontadorTag extends TagSupport {
/** This variable contains the parent (enclosing) tag. */
private RepetirTag repetirTagPadre = null;
public ValorcontadorTag() {
super();
}
////////////////////////////////////////////////////////////////
/// ///
/// User methods. ///
/// ///
/// Modify these methods to customize your tag handler. ///
/// ///
////////////////////////////////////////////////////////////////
//
// methods called from doStartTag()
//
/**
*
* Fill in this method to perform other operations from doStartTag().
*
*/
public void otherDoStartTagOperations() {
//
// TODO: code that performs other operations in doStartTag
// should be placed here.
// It will be called after initializing variables,
// finding the parent, setting IDREFs, etc, and
// before calling theBodyShouldBeEvaluated().
//
// For example, to print something out to the JSP, use the following:
//
try {
JspWriter out = pageContext.getOut();
if(repetirTagPadre != null)
{
out.println("" + repetirTagPadre.getNumeroveces());
}
} catch (java.io.IOException ex) {
// do something
}
}
/**
*
* Fill in this method to determine if the tag body should be evaluated
* Called from doStartTag().
*
*/
public boolean theBodyShouldBeEvaluated() {
//
// TODO: code that determines whether the body should be
// evaluated should be placed here.
// Called from the doStartTag() method.
//
return true;
}
//
// methods called from doEndTag()
//
/**
*
* Fill in this method to perform other operations from doEndTag().
*
*/
public void otherDoEndTagOperations() {
//
// TODO: code that performs other operations in doEndTag
// should be placed here.
// It will be called after initializing variables,
// finding the parent, setting IDREFs, etc, and
// before calling shouldEvaluateRestOfPageAfterEndTag().
//
}
/**
*
* Fill in this method to determine if the rest of the JSP page
* should be generated after this tag is finished.
* Called from doEndTag().
*
*/
public boolean shouldEvaluateRestOfPageAfterEndTag() {
//
// TODO: code that determines whether the rest of the page
// should be evaluated after the tag is processed
// should be placed here.
// Called from the doEndTag() method.
//
return true;
}
////////////////////////////////////////////////////////////////
/// ///
/// Tag Handler interface methods. ///
/// ///
/// Do not modify these methods; instead, modify the ///
/// methods that they call. ///
/// ///
////////////////////////////////////////////////////////////////
/** .
*
* This method is called when the JSP engine encounters the start tag,
* after the attributes are processed.
* Scripting variables (if any) have their values set here.
* @return EVAL_BODY_INCLUDE if the JSP engine should evaluate the tag body, otherwise return SKIP_BODY.
* This method is automatically generated. Do not modify this method.
* Instead, modify the methods that this method calls.
*
*
*/
public int doStartTag() throws JspException, JspException {
//
// Then we find the parent (enclosing tag)
//
if (repetirTagPadre == null) {
repetirTagPadre = (RepetirTag)findAncestorWithClass(this, RepetirTag.class);
}
otherDoStartTagOperations();
if (theBodyShouldBeEvaluated()) {
return EVAL_BODY_INCLUDE;
} else {
return SKIP_BODY;
}
}
/** .
*
*
* This method is called after the JSP engine finished processing the tag.
* @return EVAL_PAGE if the JSP engine should continue evaluating the JSP page, otherwise return SKIP_PAGE.
* This method is automatically generated. Do not modify this method.
* Instead, modify the methods that this method calls.
*
*
*/
public int doEndTag() throws JspException, JspException {
otherDoEndTagOperations();
if (shouldEvaluateRestOfPageAfterEndTag()) {
return EVAL_PAGE;
} else {
return SKIP_PAGE;
}
}
}
|
Modificamos nuestro JSP
| <%@page contentType="text/html"%> <%@taglib uri="tagsroberto.tld" prefix="rc"%> <html> <head><title>JSP Page</title></head> <body> <rc:repetir numeroveces="4"> Esta cadena la repetiremos varias veces <rc:valorcontador/> <br> </rc:repetir> </body> </html> |
Vemos el resultado.... en este caso... el valor decrementa por la lógica que le hemos dado.

La verdad es que los Wizards que tienen ahora la herramientas son un pasada ..... pero procurad no abusar de ellos ... porque después ... cuando se cambia de proyecto ..... y se usa otra herramienta .... podemos parecer patosos..
Podéis descargaos todo el código aquí.
Anímate y coméntanos lo que pienses sobre este tutorial
Puedes opinar o comentar cualquier sugerencia que quieras comunicarnos sobre este tutorial; con tu ayuda, podemos ofrecerte un mejor servicio.
| Autor | Mensaje de usuario registrado |
|---|
- Puedes inscribirte en nuestro servicio de notificaciones haciendo clic aquí.
- Puedes firmar en nuestro libro de visitas haciendo clic aquí.
- Puedes asociarte al grupo AdictosAlTrabajo en XING haciendo clic aquí.
- Añadir a favoritos Technorati.
Esta obra está licenciada bajo licencia Creative Commons de
Reconocimiento-No comercial-Sin obras derivadas 2.5
Recuerda
Autentia te regala la mayoría del conocimiento aquí compartido (Ver todos los tutoriales). Somos expertos en: J2EE, Struts, JSF, C++, OOP, UML, UP, Patrones de diseño ... y muchas otras cosas.
¿Nos vas a tener en cuenta cuando necesites consultoría o formación en tu empresa?, ¿Vas a ser tan generoso con nosotros como lo tratamos de ser con vosotros?
Somos pocos, somos buenos, estamos motivados y nos gusta lo que hacemos ...
Autentia = Soporte a Desarrollo & Formación.
Tutoriales recomendados
| Nombre | Resumen | Visitas | Valoración | Votos | ||
|---|---|---|---|---|---|---|
| Introducción a RichFaces. | RichFaces es una librería de componentes visuales para JSF con soporte para Ajax4JSF. | 2010-02-01 | 461 | - | - | ![]() |
| Tutorial basico de google wave bots | En este tutorial crearemos un robot muy simple, que al invitarlo a un Wave sustituye una tag por la fecha y hora actual. | 2009-11-18 | 2302 | - | - | ![]() |
| Migración de JSP a Facelets | Si tienes alguna aplicación que mantener basada en JSF y construida en JSPs, este tutorial te servirá para evaluar el coste de su migración a Facelets | 2008-10-22 | 7143 | Bueno | 1 | ![]() |
| Metro: pila de webservices de Sun. Integración con Maven 2 | En este tutorial Germán nos enseñara a integrar la generación de webservices con Metro y Maven2. | 2008-04-05 | 3233 | - | - | ![]() |
| Jersey: la implemetación de RESTFull de Sun | En este tutorial Germán nos enseña cómo usar RESTFull con la tecnología de Sun. | 2008-04-05 | 2615 | - | - | ![]() |
| Genera gráficas como las de Google Chart con Eastwood | Si no conoces JFreeChart pero quieres hacer gráficas tan llamativas como las de Google Chart, Eastwood te resultará muy útil | 2008-04-03 | 3828 | - | - | ![]() |
| Introducción a JPivot | Nuestro compañero Juan nos enseña la librería JPivot que se utiliza para mostrar tablas dinámicas en Java | 2008-03-04 | 10261 | - | - | ![]() |
| Ejemplo de web con ICEfaces | Creación de una web paso a paso con ICEFaces, Tomcat 5.5 y Eclipse | 2008-01-16 | 19241 | - | - | ![]() |
| Integración de JSF 1.2, Facelets e ICEFaces en Tomcat 6 | Integración de JSF 1.2, Facelets e ICEFaces en Tomcat 6 | 2007-12-10 | 14040 | - | - | ![]() |
| Manual básico de Spring WebFlow | En este tutorial Javier Antoniucci nos enseña cómo empezar a trabajar cpn el framework de desarrollo web Spring webflow. | 2007-11-26 | 9814 | Regular | 1 | ![]() |
Nota:
Los tutoriales mostrados en este Web tienen como objetivo la difusión del conocimiento.
Los contenidos y comentarios de los tutoriales son responsabilidad de sus respectivos autores.
En algún caso se puede hacer referencia a marcas o nombres cuya propiedad y derechos es de sus respectivos dueños. Si algún afectado desea que incorporemos alguna reseña específica, no tiene más que solicitarlo.
Si alguien encuentra algún problema con la información publicada en este Web, rogamos que informe al administrador rcanales@adictosaltrabajo.com para su resolución.







