Estas en:

Catálogo de servicios
Autentia (PDF 6,2MB)

tríptico de Autentia
En formato comic...

Acceso de usuarios registrados:

Deseo registrarme

He olvidado mis datos de acceso

Registra tu empresa:

Descubre las ventajas de registrar tu empresa en AdictosAlTrabajo...

Registrar mi empresa

Listado de empresas ya registradas

Google

Últimos tutoriales

+Noticias Destacadas

+Comentarios Cómic

  2009-08-28 - 11:17:42 AM
   rcanales escribío:
    Completamente de acuerdo contigo. Yo no se quien hace las cuentas en tu empresa [...]
  2009-08-28 - 07:01:44 AM
   Anonimo escribío:
    pues yo tengo el cuello rigido como una piedra porque el aire acondicionado esta [...]
  2009-07-23 - 10:32:12 PM
   Jaime escribío:
    definitivamente la parte mas divertida es la de programar, y la explotacion lo v [...]
  2009-05-13 - 11:26:33 PM
   williarim escribío:
    Quiero felicitar al autor de estas historietas! Gracias por compartir con todos [...]
  2009-05-13 - 04:40:59 PM
   rcanales escribío:
    Hola Brunoise: Todo tiene perspectiva. El función de tus forma de ser y ver e [...]

+Enlaces


Tutorial desarrollado por

Roberto Canales Mora

Creador y propietario de AdictosAlTrabajo.com, Director General de Autentia S.L., Ingeniero Técnico de Telecomunicaciones y Executive MBA por el Instituto de Empresa 2007. Perfíl Technorati

Experto en formación en: Dirección de proyectos informáticos, análisis y diseño UML, arquitectura Web, patrones de diseño y JEE a todos los niveles.

Puedes consultar mi CV y alguna de mis primeras aplicaciones (de los 90) aquí

Catálogo de servicios de Autentia

Descargar (6,2 MB)

Descargar en versión comic (17 MB)

AdictosAlTrabajo.com es el Web de difusión de conocimiento de Autentia.

Catálogo de cursos

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() + "");
  
   //
   // write the body content (after processing by the JSP engine) on the output Writer
   //
   bodyContent.writeOut(out);

   //
   // Or else get the body content as a string and process it, e.g.:
   //String bodyStr = bodyContent.getString();
   //String result = yourProcessingMethod(bodyStr);
   //out.println(result);
   //

   // TODO: insert code to write html after writing the body content.
   //  e.g.  out.println("   ");
   // clear the body content for the next time through.
   bodyContent.clearBody();
    }

    /** .
*
* Handles exception from processing the body content.
*
*
*/
    public void handleBodyContentException(Exception ex) throws JspException {
   // Since the doAfterBody method is guarded, place exception handing code here.
   throw new JspException("error in RepetirTag: " + ex);
    }

    /** .
*
*
* This method is called after the JSP engine processes the body content of the tag.
* @return EVAL_BODY_AGAIN if the JSP engine should evaluate the tag body again, otherwise return SKIP_BODY.
* This method is automatically generated. Do not modify this method.
* Instead, modify the methods that this method calls.
*
*
*/
    public int doAfterBody() throws JspException {
   try {
  //
  // This code is generated for tags whose bodyContent is "JSP"
  //
  BodyContent bodyContent = getBodyContent();
  JspWriter out = bodyContent.getEnclosingWriter();

  writeTagBodyContent(out, bodyContent);
   } catch (Exception ex) {
  handleBodyContentException(ex);
   }

   if (theBodyShouldBeEvaluatedAgain()) {
  return EVAL_BODY_AGAIN;
   } else {
  return SKIP_BODY;
   }
    }

    /**
* Fill in this method to determine if the tag body should be evaluated
* again after evaluating the body.
* Use this method to create an iterating tag.
* Called from doAfterBody().
*
*
*/
    public boolean theBodyShouldBeEvaluatedAgain() {
   //
   // TODO: code that determines whether the tag body should be
   //  evaluated again after processing the tag
   //  should be placed here.
   //  You can use this method to create iterating tags.
   //  Called from the doAfterBody() method.
   //
   return false;
    }
}

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í.

Sobre el Autor ..

¿Qué te ha parecido el tutorial? Déjanos saber tu opinión y ¡vota!

Muy malo Malo Regular Bueno Muy bueno
 


(Sólo para usuarios registrados)

» Registrate y accede a esta y otras ventajas «

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.


(Sólo para usuarios registrados)

» Registrate y accede a esta y otras ventajas «

Autor Mensaje de usuario registrado

Creative Commons License 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.

info@autentia.com

Tutoriales recomendados

Nombre Resumen
Fecha
Visitas Valoración Votos Pdf
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.