Tuesday, September 24, 2013

JSTL forTokens Tag Example - Split String in JSP

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. For example to iterate over colon separated String "abc:cde:fgh:ijk", delims=":". By the way, forTokens tag also accept multiple delimiter, which means, you can split a big string into token based upon multiple delimiter e.g. colon(:) and pipe (|), This will be more clear, when we will see examples of JSTL forTokens tag in JSP. Rest of attribute e.g. items, var, varStatus, begin, end and step are same, as they are in case of <c:forEach> tag. For quick review, items specify String which needs to be split-ed in token and var hold current String.

JSTL <c:forTokens> Tag Example

JSTL forTokens examples JSPHere is our complete code example of using JSTL forTokens tag in JSP page. In this example, we first split a comma separate String using forTokens tag by specifying delims=";". When we iterate over tokens, var represent current token. In the second example, we have specified multiple delimiter in delims attribute, delims="|," to split String by pipe(|) character and comma (,) character.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title> JSTL forTokens tag Example - Iterate over comma separated String in JSP</title>


        <h3> forTokens Tag Example</h3>

        <h4>String with comma ',' delimiter</h4>

        <c:forTokens var="token" items="Java, J2EE, JSTL, JSP, Servlet"
            <c:out value="${token}"/> </br>

        <h4>Iterating over String with '|' and ',' delimiters</h4>

        <c:forTokens var="token" items="USA,New York,UK|London,Japan|Tokyo"
            <c:out value="${token}"/> </br>

forTokens Tag Example
String with comma ',' delimiter

Iterating over String with '|' and ',' delimiters
New York

That's all on How to use JSTL forTokens tag for iterating over comma separated String. Good thing about forTokens tag is that, it not only complements forEach tag, but also support multiple delimiters for breaking String into tokens. Quite handy to process request parameters and other text data.

Further Learning
Java Web Fundamentals By Kevin Jones
Introduction to Spring MVC 4
Head First Servlet and JSP

No comments :

Post a Comment