Uso de Tags de Dados e Controle no Framework Struts2

Tags Struts2 - Dados e ControleVisão Geral das Tags Struts2

As tags do Struts2 oferecem funcionalidades extensivas para desenvolvimento web em Java, mas podem impactar o desempenho comparado a alternativas como JSTL, apresentendo sobrecarga em tempo de execução.

Tags de Dados no Struts2

As tags de dados são usadas para exibir e manipular informações na camada de visão. Exemplos incluem <s:property>, <s:set>, <s:bean>, <s:date>, <s:debug>, <s:url> e <s:a>, e <s:include>.

Classe de Modelo: Aluno.java


package com.modelo;

public class Aluno {

    private int codigo;
    private String nome;
    private int idade;

    public Aluno() {
    }

    public Aluno(int codigo, String nome, int idade) {
        this.codigo = codigo;
        this.nome = nome;
        this.idade = idade;
    }

    public int getCodigo() {
        return codigo;
    }

    public void setCodigo(int codigo) {
        this.codigo = codigo;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public int getIdade() {
        return idade;
    }

    public void setIdade(int idade) {
        this.idade = idade;
    }
}

Exemplos de Uso

Tag Property

A tag <s:property> exibe valores de variáveis. Exemplo em JSP:


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Propriedades</title>
</head>
<body>
    <% request.setAttribute("valor", "<font color=blue>Texto em azul</font>"); %>
    <s:property value="#request.valor" /><br/>
    <s:property value="#request.outro" default="Valor padrão"/><br/>
    <s:property value="#request.valor" default="Substituto" escapeHtml="false"/><br/>
</body>
</html>

Tag Set

A tag <s:set> define variáveis em diferentes escopos.


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Definição de Variáveis</title>
</head>
<body>
    <s:set var="numero" value="42"></s:set>
    <s:property value="#numero" /><br/>
    <s:set var="acao" value="'Valor na ação'" scope="action"></s:set>
    <s:set var="pagina" value="'Valor na página'" scope="page"></s:set>
    <s:set var="requisicao" value="'Valor na requisição'" scope="request"></s:set>
    <s:set var="sessao" value="'Valor na sessão'" scope="session"></s:set>
    <s:set var="aplicacao" value="'Valor na aplicação'" scope="application"></s:set>
    <s:property value="#acao" /><br/>
    <s:property value="#attr.pagina"/><br/>
    <s:property value="#request.requisicao"/><br/>
    <s:property value="#session.sessao"/><br/>
    <s:property value="#application.aplicacao"/><br/>
</body>
</html>

Tag Bean

A tag <s:bean> instancia objetos Java.


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Instanciamento de Beans</title>
</head>
<body>
    <s:bean name="com.modelo.Aluno" var="aluno">
        <s:param name="nome" value="'Maria'"></s:param>
        <s:param name="idade" value="15"></s:param>
    </s:bean>
    <s:property value="#aluno.nome"/>
    <s:property value="#aluno.idade"/>
</body>
</html>

Tag Date

A tag <s:date> formata datas.


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page import="java.util.*" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Formatação de Datas</title>
</head>
<body>
    <% request.setAttribute("dataAtual", new Date()); %>
    ${dataAtual}<br/>
    Data formatada: <s:date name="#request.dataAtual" format="dd-MM-yyyy"/><br>
    Outro formato: <s:date name="#request.dataAtual" format="yyyy/MM/dd"/>
</body>
</html>

Tag Debug

A tag <s:debug> exibe informações de depuração do ValueStack.


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Depuração</title>
</head>
<body>
    <s:debug></s:debug>
</body>
</html>

Tags URL e A

As tags <s:url> e <s:a> geram URLs e links.


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Geração de URLs</title>
</head>
<body>
    <s:url action="exemplo" namespace="/front" id="link1">
        <s:param name="parametro" value="'teste'"></s:param>
    </s:url>
    <s:a href="%{link1}">Link via URL</s:a>

    <s:a action="exemplo" namespace="/front">
        <s:param name="parametro" value="'teste'"></s:param>
        Link direto
    </s:a>
</body>
</html>

Tag Include

A tag <s:include> inclui conteúdo de outros recursos.


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Inclusão de Conteúdo</title>
</head>
<body>
    <s:include value="cabecalho.html"></s:include>
</body>
</html>

Conteúdo de cabecalho.html:


<body>
Cabeçalho
</body>

Tags de Controle no Struts2

As tags de controle gerenciam fluxo e iteração em páginas JSP. Exemplos incluem <s:if>, <s:iterator>, <s:append>, <s:merge>, <s:generator>, <s:sort> e <s:subset>.

Classe Comparadora: ComparadorAluno.java


package com.comparador;

import java.util.Comparator;
import com.modelo.Aluno;

public class ComparadorAluno implements Comparator<Aluno> {

    public int compare(Aluno a1, Aluno a2) {
        if (a1.getIdade() > a2.getIdade()) {
            return 1;
        } else if (a1.getIdade() < a2.getIdade()) {
            return -1;
        }
        return 0;
    }
}

Exemplos de Uso

Tag If/Else

A tag <s:if> avalia condições.


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Condições</title>
</head>
<body>
    <% request.setAttribute("idade", 25); %>
    <s:if test="#request.idade < 30">
        Idade menor que 30 anos
    </s:if>
    <s:elseif test="#request.idade == 30">
        Idade igual a 30 anos
    </s:elseif>
    <s:else>
        Idade maior que 30 anos
    </s:else>
</body>
</html>

Tag Iterator

A tag <s:iterator> percorrre coleções.


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page import="com.modelo.Aluno" %>
<%@ page import="java.util.*" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Iteração</title>
</head>
<body>
    <%
        List<Aluno> listaAlunos = new ArrayList<Aluno>();
        listaAlunos.add(new Aluno(101, "Ana", 18));
        listaAlunos.add(new Aluno(102, "Carlos", 22));
        listaAlunos.add(new Aluno(103, "Elena", 25));
        request.setAttribute("listaAlunos", listaAlunos);
    %>
    <table>
        <tr>
            <th>Índice</th>
            <th>Código</th>
            <th>Nome</th>
            <th>Idade</th>
        </tr>
        <s:iterator value="#request.listaAlunos" status="status">
        <tr>
            <td><s:property value="#status.index+1"/></td>
            <td><s:property value="codigo"/></td>
            <td><s:property value="nome"/></td>
            <td><s:property value="idade"/></td>
        </tr>
        </s:iterator>
    </table>
</body>
</html>

Tag Append

A tag <s:append> combina listas sequencialmente.


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page import="com.modelo.Aluno" %>
<%@ page import="java.util.*" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Concatenação de Listas</title>
</head>
<body>
    <%
        List<Aluno> listaA = new ArrayList<Aluno>();
        List<Aluno> listaB = new ArrayList<Aluno>();
        listaA.add(new Aluno(1, "João", 20));
        listaA.add(new Aluno(2, "Ana", 22));
        listaB.add(new Aluno(3, "Pedro", 25));
        listaB.add(new Aluno(4, "Sofia", 28));
        request.setAttribute("listaA", listaA);
        request.setAttribute("listaB", listaB);
    %>
    <s:append var="listaCombinada">
        <s:param value="#request.listaA"></s:param>
        <s:param value="#request.listaB"></s:param>
    </s:append>
    <table>
        <tr>
            <th>Índice</th>
            <th>Código</th>
            <th>Nome</th>
            <th>Idade</th>
        </tr>
        <s:iterator value="listaCombinada" status="status">
        <tr>
            <td><s:property value="#status.index+1"/></td>
            <td><s:property value="codigo"/></td>
            <td><s:property value="nome"/></td>
            <td><s:property value="idade"/></td>
        </tr>
        </s:iterator>
    </table>
</body>
</html>

Tag Generator

A tag <s:generator> cria listas a partir de strings.


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Geração de Dados</title>
</head>
<body>
    <s:generator separator=";" val="'Item1;Item2;Item3'" var="itens"></s:generator>
    <s:iterator value="#itens">
        <s:property/><br/>
    </s:iterator>
</body>
</html>

Tag Merge

A tag <s:merge> intercala elementos de listas.


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page import="com.modelo.Aluno" %>
<%@ page import="java.util.*" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Intercalação de Listas</title>
</head>
<body>
    <%
        List<Aluno> lista1 = new ArrayList<Aluno>();
        List<Aluno> lista2 = new ArrayList<Aluno>();
        lista1.add(new Aluno(10, "Lucas", 19));
        lista1.add(new Aluno(11, "Marta", 21));
        lista2.add(new Aluno(12, "Paulo", 24));
        lista2.add(new Aluno(13, "Rita", 27));
        request.setAttribute("lista1", lista1);
        request.setAttribute("lista2", lista2);
    %>
    <s:merge var="listaMista">
        <s:param value="#request.lista1"></s:param>
        <s:param value="#request.lista2"></s:param>
    </s:merge>
    <table>
        <tr>
            <th>Índice</th>
            <th>Código</th>
            <th>Nome</th>
            <th>Idade</th>
        </tr>
        <s:iterator value="listaMista" status="status">
        <tr>
            <td><s:property value="#status.index+1"/></td>
            <td><s:property value="codigo"/></td>
            <td><s:property value="nome"/></td>
            <td><s:property value="idade"/></td>
        </tr>
        </s:iterator>
    </table>
</body>
</html>

Tag Sort

A tag <s:sort> ordena coleções com um comparador.


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page import="com.modelo.Aluno" %>
<%@ page import="java.util.*" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Ordenação</title>
</head>
<body>
    <%
        List<Aluno> listaOrdenar = new ArrayList<Aluno>();
        listaOrdenar.add(new Aluno(20, "Bruno", 30));
        listaOrdenar.add(new Aluno(21, "Carla", 18));
        listaOrdenar.add(new Aluno(22, "Diogo", 40));
        listaOrdenar.add(new Aluno(23, "Fernanda", 25));
        request.setAttribute("listaOrdenar", listaOrdenar);
    %>
    <s:bean id="comp" name="com.comparador.ComparadorAluno"></s:bean>
    <table>
        <tr>
            <th>Índice</th>
            <th>Código</th>
            <th>Nome</th>
            <th>Idade</th>
        </tr>
        <s:sort comparator="#comp" source="#request.listaOrdenar">
        <s:iterator status="status">
        <tr>
            <td><s:property value="#status.index+1"/></td>
            <td><s:property value="codigo"/></td>
            <td><s:property value="nome"/></td>
            <td><s:property value="idade"/></td>
        </tr>
        </s:iterator>
        </s:sort>
    </table>
</body>
</html>

Tag Subset

A tag <s:subset> extrai subconjuntos de coleções.


<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page import="com.modelo.Aluno" %>
<%@ page import="java.util.*" %>
<%@taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
    <title>Subconjuntos</title>
</head>
<body>
    <%
        List<Aluno> listaSub = new ArrayList<Aluno>();
        listaSub.add(new Aluno(30, "Gabriel", 35));
        listaSub.add(new Aluno(31, "Helena", 42));
        listaSub.add(new Aluno(32, "Igor", 28));
        listaSub.add(new Aluno(33, "Julia", 33));
        request.setAttribute("listaSub", listaSub);
    %>
    <table>
        <tr>
            <th>Índice</th>
            <th>Código</th>
            <th>Nome</th>
            <th>Idade</th>
        </tr>
        <s:subset source="#request.listaSub" count="3" start="1">
        <s:iterator status="status">
        <tr>
            <td><s:property value="#status.index+1"/></td>
            <td><s:property value="codigo"/></td>
            <td><s:property value="nome"/></td>
            <td><s:property value="idade"/></td>
        </tr>
        </s:iterator>
        </s:subset>
    </table>
</body>
</html>

Tags: Struts2 jsp java OGNL data-tags

Publicado em 6-25 18:30