JSTL: tag Core <c: forEach>, <c: forTokens>
Questi tag esistono come una buona alternativa all'incorporamento di Java for, while, o do-whileloop tramite uno scriptlet. Il<c:forEach>tag è un tag comunemente usato perché itera su una raccolta di oggetti. Il<c:forTokens> tag viene utilizzato per suddividere una stringa in token e iterare su ciascuno di essi.
Attributo
Il <c:forEach> tag ha i seguenti attributi:
Attributo | Descrizione | necessario | Predefinito |
---|---|---|---|
elementi | Informazioni su cui eseguire il loop | No | Nessuna |
inizio | Elemento con cui iniziare (0 = primo elemento, 1 = secondo elemento, ...) | No | 0 |
fine | Elemento con cui terminare (0 = primo elemento, 1 = secondo elemento, ...) | No | Ultimo elemento |
passo | Elabora ogni elemento del passaggio | No | 1 |
var | Nome della variabile per esporre l'elemento corrente | No | Nessuna |
varStatus | Nome della variabile per esporre lo stato del ciclo | No | Nessuna |
Il <c:forTokens> ha attributi simili a quelli del tag <c:forEach> tag tranne un attributo aggiuntivo delims che specifica i caratteri di condivisione da utilizzare come delimitatori.
Attributo | Descrizione | necessario | Predefinito |
---|---|---|---|
delim | Caratteri da utilizzare come delimitatori | sì | Nessuna |
Esempio per <c: forEach>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<html>
<head>
<title><c:forEach> Tag Example</title>
</head>
<body>
<c:forEach var = "i" begin = "1" end = "5">
Item <c:out value = "${i}"/><p>
</c:forEach>
</body>
</html>
Il codice sopra genererà il seguente risultato:
Item 1
Item 2
Item 3
Item 4
Item 5
Esempio per <c: forTokens>
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<html>
<head>
<title><c:forTokens> Tag Example</title>
</head>
<body>
<c:forTokens items = "Zara,nuha,roshy" delims = "," var = "name">
<c:out value = "${name}"/><p>
</c:forTokens>
</body>
</html>
Il codice sopra genererà il seguente risultato:
Zara
nuha
roshy