TagLib como fazer uma?

8 respostas
aorocha

Pessoal estou querendo fazer a minha tagLib personalizada, alguem de um tutorial ou exemplo?

8 Respostas

zirocool

Pode ser o tutorial oficial da sun, e em inglês?/

http://java.sun.com/javaee/5/docs/tutorial/doc/JSPTags2.html

baladao

Minha primeira taglib:

Custom Tag
package org.myframework;

import java.io.IOException;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * @author Juliano V. Baladão
 * @version 1.0
 * 
 * Descrição: TagLib responsavel por criar um painel com abas.
 */
public class TagTestePai extends TagSupport {

    private String id = null;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

	/**
     * @return int
     * 
     * @throws javax.servlet.jsp.JspException
     */
    public int doStartTag() throws javax.servlet.jsp.JspException {
    	StringBuffer sb = new StringBuffer();

    	sb.append("Start_Pai<br>\n");
        
        try {
            pageContext.getOut().write(sb.toString());
        } catch (IOException ioException) {
            System.out.println("Error: TagTestePai.doEndTag() -> "
                    + ioException.getMessage());
        }
        
    	return EVAL_BODY_INCLUDE;
    }

    /**
     * @return int
     * 
     * @throws javax.servlet.jsp.JspException
     */
    public int doEndTag() throws javax.servlet.jsp.JspException {
    	StringBuffer sb = new StringBuffer();
    	
        sb.append("End_Pai<br>\n");
        
        try {
            pageContext.getOut().write(sb.toString());
        } catch (IOException ioException) {
            System.out.println("Error: TagTestePai.doEndTag() -> "
                    + ioException.getMessage());
        }

        this.release();
        return EVAL_PAGE;
    }

    public void release() {
        super.release();
        
        this.id = null;
    }

}
Custom SubTag
package org.myframework;

import java.io.IOException;
import javax.servlet.jsp.tagext.TagSupport;

/**
 * @author Juliano V. Baladão
 * @version 1.0
 * 
 * Descrição: TagLib responsavel por criar um painel com abas.
 */
public class TagTesteFilho extends TagSupport {

    private String id = null;
    private TagTestePai parent = null;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

	/**
     * @return int
     * 
     * @throws javax.servlet.jsp.JspException
     */
    public int doStartTag() throws javax.servlet.jsp.JspException {
    	StringBuffer sb = new StringBuffer();

        if (getParent() == null) {
	    	sb.append("Start_Filho_null<br>\n");
        } else {
        	TagTestePai pai = (TagTestePai) getParent();
        	sb.append("Start_Filho_" + pai.getId() + "<br>\n");
        }
        
        try {
            pageContext.getOut().write(sb.toString());
        } catch (IOException ioException) {
            System.out.println("Error: TagTreeRoot.doEndTag() -> "
                    + ioException.getMessage());
        }
        
    	return EVAL_BODY_INCLUDE;
    }

    /**
     * @return int
     * 
     * @throws javax.servlet.jsp.JspException
     */
    public int doEndTag() throws javax.servlet.jsp.JspException {
    	StringBuffer sb = new StringBuffer();
    	
        if (this.parent == null) {
	    	sb.append("End_Filho_null<br>\n");
        } else {
        	TagTestePai pai = (TagTestePai) getParent();
        	sb.append("End_Filho_" + pai.getId() + "<br>\n");
        }
        
        try {
            pageContext.getOut().write(sb.toString());
        } catch (IOException ioException) {
            System.out.println("Error: TagTreeRoot.doEndTag() -> "
                    + ioException.getMessage());
        }

        this.release();
        return EVAL_PAGE;
    }

    public void release() {
        super.release();
        
        this.id = null;
        this.parent = null;
    }

}
TLD
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">
<taglib>
    <tlibversion>2.0</tlibversion>
    <jspversion>1.5</jspversion>
    <shortname></shortname>
    <uri>myFramework</uri>

<tag>
    <name>testePai</name>
    <tagclass>org.myframework.TagTestePai</tagclass>
	<bodycontent>jsp</bodycontent>
    <attribute>
      <name>id</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
</tag>

<tag>
    <name>testeFilho</name>
    <tagclass>org.myframework.TagTesteFilho</tagclass>
    <attribute>
      <name>id</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
</tag>

</taglib>
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
     PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_4.dtd">

<web-app id="WebApp_ID" version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <welcome-file-list>
  	<welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- ============================================================== -->
  <!-- Tag Libraries			                                      -->
  <!-- ============================================================== -->  
  <taglib>
    <taglib-uri>myFramework</taglib-uri>
    <taglib-location>/WEB-INF/tld/MyFramework.tld</taglib-location>
  </taglib> 
  
   
</web-app>
marcelo_mococa

prefira estender SimpleTagSuport

é bem mais simples…

baladao

marcelo_mococa:
prefira estender SimpleTagSuport

é bem mais simples…

Em que exatamente fica mais simples?

Outra questão, vc já utilizou atributos dinâmicos, sabe qual o evento que dispara o “eval” da propriedade de RUN-TIME EXP ?

Fiz uma subtag que só insere dados na tag pai e esta por sua vez no doEndTag joga pra pageContext. O problema é que nesse caso os atributos dinâmicos das tags filhas não são validados, vem como text o código <%=…%>

marcelo_mococa

nolink q o zirocol passou tem explicando…

http://java.sun.com/javaee/5/docs/tutorial/doc/JSPTags7.html

baladao

Já tinha visto o link, mas ele não exclarece as minhas dúvidas, acho que precisaria de algo mais prático… :frowning:

fviana

use tagfile invez de taglib, é o mais simples que existe… até o momento é claro…

baladao

Esclareci-me!!!

Quando se define que um atributo é interpretado em RUN-TIME true não se pode enviar dados mistos no atributo como o abaixo:
<my:tag attr=“static?var=<%=dinamic %>” />

O certo é:
<my:tag attr="<%=“static?var=”+ dinamic %>" />

Criado 20 de julho de 2006
Ultima resposta 21 de jul. de 2006
Respostas 8
Participantes 5