Uso de los atributos de etiqueta

1969 vistas

Este ejemplo se basa en el mostrado en [iurl=90&all=0&fs=1129#1133]Escribir un Tag[/iurl].
Vamos a mejorar nuestro tag anterior añadiéndole un atributo name. Si name existe, mostraremos "Hello " seguido del valor de name, sino mostraremos "Hello World".

El código será el siguiente:



java
  1. public class HelloTag extends TagSupport {
  2.   private String name = null;
  3.  
  4.   public void setName(String string) {
  5.       name = string;
  6.   }
  7.  
  8.   public int doStartTag() throws JspException {
  9.       if (name==null)
  10.           name = "World";
  11.       try {
  12.           pageContext.getOut().println ("Hello " + name + " !");
  13.       } catch (IOException e) {
  14.           throw new JspException ("I/O Error", e);
  15.       }
  16.       return SKIP_BODY;
  17.   }
  18. }



Explicación:

  • Añadimos una variable name asà como su mutador setName().
      El mutador setName() es necesario porque se usará para inicializar el atributo de la clase con el valor del atributo del tag antes de llamar a doStartTag().
  • En doStartTag(), mostraremos "Hello " + name + " !"...

Ahora modificamos el TLD de esta forma:



xml
  1. <tag>
  2.   <name>hello</name>
  3.   <tagclass>HelloTag</tagclass>
  4.   <bodycontent>empty</bodycontent>
  5.   <attribute>
  6.     <name>name</name>
  7.   </attribute>
  8. </tag>



La página JSP queda:



html4strict
  1. <%@ taglib uri="taglib-URI" prefix="p" %>
  2.   <b><p:hello/></b>
  3.   <b><p:hello name="Fred"/></b>
  4. </body>
  5. </html>



dará como resultado:



delphi
  1. Hello World !
  2. Hello Fred !