Crear un tag condicional

2034 vistas

Podemos necesitar ejecutar un trozo de código si se da una determinada condición.
Por ejemplo, vamos a ejecutar el cuerpo de un tag sólo si el atributo indicado por parámetro existe en la sesión:



java
  1. public class IsPresentTag extends TagSupport {
  2.  
  3.   private String name = "World";
  4.  
  5.   public void setName(String string) {
  6.       name = string;
  7.   }
  8.  
  9.   public int doStartTag() throws JspException {
  10.       if (name==null)
  11.           throw new JspException ("name es null !");
  12.       if ( pageContext.getAttribute(name,PageContext.SESSION_SCOPE) != null )
  13.           return EVAL_BODY_INCLUDE;
  14.       return SKIP_BODY;
  15.   }
  16. }



AsÃ, el código siguiente:



html4strict
  1. <p:isPresent name="infoConnection">
  2. [ Estás en línea ]
  3. </p:isPresent>



reemplaza este otro:



html4strict
  1. <% if ( session.getAttribute("infoConnection") ) { %>
  2. [ Estás en línea ]
  3. <% } %>