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.
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:
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.
packageformat;importjava.text.DecimalFormat;importjava.util.Locale;importjava.io.IOException;importjava.io.PrintWriter;importjavax.servlet.ServletRequest;importjavax.servlet.jsp.JspException;importjavax.servlet.jsp.JspWriter;importjavax.servlet.jsp.PageContext;importjavax.servlet.jsp.tagext.BodyContent;importjavax.servlet.jsp.tagext.BodyTag;importjavax.servlet.jsp.tagext.BodyTagSupport;importjavax.servlet.jsp.tagext.IterationTag;importjavax.servlet.jsp.tagext.Tag;importjavax.servlet.jsp.tagext.TagSupport;/** * Generated tag class. */publicclassMoneyTagimplementsTag{/** * property declaration for tag attribute: value. */privatejava.lang.Stringvalue;/** * property declaration for tag attribute: var. */privatejava.lang.Stringvar;/** * This variable contains the parent (enclosing) tag. */protectedTagparent;/** * This variable contains the page context. */protectedPageContextpageContext;privateDecimalFormatformater;publicMoneyTag(){super();formater=newDecimalFormat("#,##0.00");}privateStringformatStringAsMoney(StringtoFormat){doublenumber=0;try{number=Double.parseDouble(toFormat);}catch(NumberFormatExceptionnfe){StringtoNumber=toFormat.trim().replaceAll(".","");toNumber=toNumber.replaceAll(",",".");try{number=Double.parseDouble(toNumber);}catch(NumberFormatExceptionnfe2){returntoFormat;}}StringtoReturn=formater.format(number).replace('.','*');toReturn=toReturn.replace(',','.');toReturn=toReturn.replace('*',',');returnformater.format(number);}/** * . * * 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. */publicintdoStartTag()throwsJspException{StringtoWrite=formatStringAsMoney(getValue());if(getVar()==null){JspWriterout=getPageContext().getOut();try{out.print(toWrite);}catch(IOExceptionioe){thrownewJspException(ioe.getMessage());}}else{getPageContext().setAttribute(getVar(),toWrite,PageContext.PAGE_SCOPE);}returnSKIP_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. */publicintdoEndTag()throwsJspException,JspException{returnEVAL_PAGE;}publicjava.lang.StringgetValue(){returnvalue;}publicvoidsetValue(java.lang.Stringvalue){if(value==null){this.value="";}else{this.value=value;}}publicjava.lang.StringgetVar(){returnvar;}publicvoidsetVar(java.lang.Stringvar){if(var.trim().equals("")){this.var=null;}else{this.var=var;}}/** * @return the parent of this tag. */publicTaggetParent(){returnparent;}/** * Set the parent of this tag. */publicvoidsetParent(Tagvalue){parent=value;}/** * Release data kept by the tag, so the tag instance can be reused for another reqeust. */publicvoidrelease(){setValue("");}/** * Set the page context of this tag. */publicvoidsetPageContext(PageContextvalue){pageContext=value;}/** * @return the page context object. */publicPageContextgetPageContext(){returnpageContext;}}