<html:messages>

4 respostas
R

Pessoal!

Estou apanhando feio do Struts!
´
Tem algumas que são fáceis de fazervia jsp/html que eu não estou conseguindo com o Struts.
Tipo assim, após uma requisição meu sistema pode apresentar três mensagens: SUCESSO - ALERTA - ERRO. Para cada mensagem eu possuo um bloco diferente. Exemplificando:

se SUCESSO
MOSTRA TABELA COM MENSAGEM DE SUCESSO
se ALERTA
MOSTRA TABELA COM MENSAGEM DE ALERTA
se ERRO
MOSTRA TABELA COM MENSAGEM DE ERRO

A princípio estou utilizando a tag Struts <logic:messagesPresent> . Mas como determinar um " id " para cada tido mensagem no meu método validade??? E como fazer achar esse “id” no html???

Se alguém puder me ajudar ficarei super agradecido.

Ricardo Moura

4 Respostas

C

Cria sua própria tag de mensagens que recebe o id e a mensagem como parâmetros e que formata a mensagem de acordo com o id.
E ainda usando EL fica muito legal…
Por exemplo:

&lt;t&#58;mensagem id="$&#123;mensagem.id&#125;" texto="$&#123;mensagem.texto&#125;"/&gt;
R

Cara…isso é muito avançado pra mim. Não tenho nem idéia de como fazer isso. Se tiver um exemplo básico que possa me ajudar.
Estou começando agora com o Struts, e algumas dúvidas são “cruéis”.

De qualquer forma muito obrigado.

martui

:scrambleup: Uma tag é basicamente um par tld (que é um xml)/jar. A estrutura não é assim complexa. Mas se você não sabe como fazer, basta usar o NetBeans. Nele é muito simples de fazer tudo. O tld você monta visualmente e depois manda gerar o código. Ele monta a estrutura e você preenche o método. No final deste post tem um exemplo muito simples do .java de uma tag que tenta formatar uma String como dinheiro. É bem precária, mas vale a pena olhar. Ela recebe dois atributos: value (obrigatório) e var (opcional) e não tem corpo. Se não me engano, uma taglib sempre executa seus métodos na seguinte sequência:
:arrow: setPageContext()
:arrow: todos os setters (ele tem que ter setters e getters como um bean)
:arrow: doStart()
:arrow: doEnd
:arrow: release() - para limpar o objeto da tag.

Mas acho que no seu caso isso não é preciso. Talvez você possa usar um atributo do request que defina o tipo de mensagem e usar a tag c:if da taglib core da própria Sun pra avaliar se deve passar pelo do logic para exibir erros ou se deve imprimir mensagem de alerta ou nada. Não sei se tem uma tag switch que talvez facilitasse ainda mais as coisas.

package format;

import java.text.DecimalFormat;
import java.util.Locale;

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 MoneyTag implements Tag &#123;

    /**
     * property declaration for tag attribute&#58; value.
     */    
    private java.lang.String value;
    
    /**
     * property declaration for tag attribute&#58; var.
     */ 
    private java.lang.String var;

    /**
     * This variable contains the parent &#40;enclosing&#41; tag.
     */    
    protected Tag parent;
    
    /**
     * This variable contains the page context.
     */    
    protected PageContext pageContext;
    
    private DecimalFormat formater;
    
    public MoneyTag&#40;&#41; &#123;
        super&#40;&#41;;
        formater = new DecimalFormat&#40;&quot;#,##0.00&quot;&#41;;
    &#125;

    private String formatStringAsMoney&#40;String toFormat&#41;&#123;
        double number = 0;
        try&#123;
            number = Double.parseDouble&#40;toFormat&#41;;
        &#125;
        catch&#40;NumberFormatException nfe&#41;&#123;
            String toNumber = toFormat.trim&#40;&#41;.replaceAll&#40;&quot;.&quot;, &quot;&quot;&#41;;
            toNumber = toNumber.replaceAll&#40;&quot;,&quot;, &quot;.&quot;&#41;;
            try&#123;
                number = Double.parseDouble&#40;toNumber&#41;;
            &#125;
            catch&#40;NumberFormatException nfe2&#41;&#123;
                return toFormat;
            &#125;
        &#125;

        String toReturn = formater.format&#40;number&#41;.replace&#40;'.', '*'&#41;;
        toReturn = toReturn.replace&#40;',', '.'&#41;;
        toReturn = toReturn.replace&#40;'*', ','&#41;;
        
        return formater.format&#40;number&#41;;
    &#125;
    
    /**
     * .
     *
     * This method is called when the JSP engine encounters the start tag,
     * after the attributes are processed.
     * Scripting variables &#40;if any&#41; have their values set here.
     * @return EVAL_BODY_INCLUDE if the JSP engine should evaluate the tag body, otherwise return SKIP_BODY.
     */
    public int doStartTag&#40;&#41; throws JspException &#123;
        String toWrite = formatStringAsMoney&#40;getValue&#40;&#41;&#41;;
        
        if&#40;getVar&#40;&#41; == null&#41;&#123;
            JspWriter out = getPageContext&#40;&#41;.getOut&#40;&#41;;
            try&#123;
                out.print&#40;toWrite&#41;;
            &#125;
            catch&#40;IOException ioe&#41;&#123;
                throw new JspException&#40;ioe.getMessage&#40;&#41;&#41;;
            &#125;
        &#125;
        else&#123;
            getPageContext&#40;&#41;.setAttribute&#40;getVar&#40;&#41;, toWrite, PageContext.PAGE_SCOPE&#41;;
        &#125;
        
        return SKIP_BODY;
    &#125;
    
    /**
     * .
     *
     *
     * 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.
     */
    public int doEndTag&#40;&#41; throws JspException, JspException &#123;
        return EVAL_PAGE;
    &#125;
    
    public java.lang.String getValue&#40;&#41; &#123;
        return value;
    &#125;
    
    public void setValue&#40;java.lang.String value&#41; &#123;
        if&#40;value == null&#41;&#123;
            this.value = &quot;&quot;;
        &#125;
        else&#123;
            this.value = value;
        &#125;
    &#125;
    
    public java.lang.String getVar&#40;&#41; &#123;
        return var;
    &#125;
    
    public void setVar&#40;java.lang.String var&#41; &#123;
        if&#40;var.trim&#40;&#41;.equals&#40;&quot;&quot;&#41;&#41;&#123;
            this.var = null;
        &#125;
        else&#123;
            this.var = var;
        &#125;
    &#125;
    
    /**
     * @return the parent of this tag.
     */    
    public Tag getParent&#40;&#41; &#123;
        return parent;
    &#125;
    
    /**
     * Set the parent of this tag.
     */    
    public void setParent&#40;Tag value&#41; &#123;
        parent = value;
    &#125;
    
    /**
     * Release data kept by the tag, so the tag instance can be reused for another reqeust.
     */    
    public void release&#40;&#41; &#123;
        setValue&#40;&quot;&quot;&#41;;
    &#125;
    
    /**
     * Set the page context of this tag.
     */    
    public void setPageContext&#40;PageContext value&#41; &#123;
        pageContext = value;
    &#125;
    
    /**
     * @return the page context object.
     */    
    public PageContext getPageContext&#40;&#41; &#123;
        return pageContext;
    &#125;
    
&#125;
C

No JSTL tem a tag <c:choose>

Criado 26 de agosto de 2004
Ultima resposta 27 de ago. de 2004
Respostas 4
Participantes 3