JSTL forTokens Tag <forTokens>

JSTL forTokens tag is used to iterate over the tokens separated by delimiters. JSTL forTokens tag is another tag in core JSTL library to support Iteration or looping. It effectively complements, more useful <c:forEach> tag, by allowing you to iterate over comma separated or any delimited String. You can use this tag to split string in JSP and can operate on them individually. forTokens tag has similar attribute like forEach JSTL tag except one more attribute called delims, which specifies delimiter.

JSTL <c:forTokens> tag Example:

To display the names on JSP, you can use the <forTokens> tag like:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<title><c:forTokens> Tag Example</title>
<c:forTokens items="Dinesh,Anamika,Sweety" delims="," var="name">
   <c:out value="${name}"/><p>
As you can see above, in the JSTL forTokens tag, items attribute is used to define the tokens. It will iterate over tokens separated by delimiter. In each iteration, it will get a token defined with attribute var. status attribute keeps track of iteration.

Withing starting and ending tag of  forTokens, you can display or apply other logic to each token.

Attributes of <c:forTokens> tag are:

Required Attributes:

      1. items:This attribute provides string of tokens to iterate over..

       2. delims: This attribute provides the set of delimiters. The characters that separate the tokens in the string.

Optional Attributes:

       1. var: This attribute provides name of the exported scoped variable for the current item of the iteration. This scoped variable has nested visiblity. Its type depends on the object of the underlying collection.

       2. varStatus: This attribute provides name of the exported scoped variable for the status of the iteration. Object exported is of type javax.servlet.jsp.jstl.core.LoopTagStatus. This scoped variable has nested visibility.

       3. begin: If items specified: Iteration begins at the item located at the specified index. First item of the collection has index 0. If items not specified: Iteration begins with index set at the value specified.

      4. end: If items specified: Iteration ends at the item located at the specified index (inclusive). If items not specified: Iteration ends when index reaches the value specified.

     5. step: Iteration will only process every step items of the collection, starting with the first one.

<<Previous <<   || Index ||   >>Next >>

No comments:

Post a Comment