JSP JSTL Functions

JSP Function JSTL

  • The JSP Standard Tag Library (JSTL) adds essential features to JSP that enable JSP programming without the need for embedded Java code.
  • It is a collection of standard JSP tags that perform several common tasks.
  • This frees us from having to develop custom tags for these tasks, or from using a mix of tags from several organizations to do our work.
  • The Function JSTL contains a number of string manipulation functions. These include functions for splitting and concatenating strings, returning substrings, determining whether a string contains a specified substring, and many others.
  • Before using the Function JSTL, the following directive needs to be added to the JSP page:
  • <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
  • The equivalent XML syntax used in tag files for this directive is:
  • <jsp:directive.taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" />

Here is a summary of all Function JSTL

  • Function Description
    contains Tests whether an input string contains the specified substring. This is a case-sensitive search.
    containsIgnoreCase Tests whether an input string contains the specified substring in a case-insensitive way.
    endsWith Tests whether an input string ends with the specified suffix.
    escapeXml Escapes characters that could be interpreted as XML markup.
    indexOf Returns the index within a string of the first occurrence of a specified substring.
    join Concatenates all elements of an array into a string.
    length Returns the number of items in a collection or the number of characters in a string.
    replace Returns a string that results from replacing in an input string all occurrences of a "before" string into an "after" substring.
    split Splits a string into an array of substrings.
    startsWith Tests whether an input string starts with the specified prefix.
    substring Returns a subset of a string.
    substringAfter Returns a subset of a string following a specific substring.
    substringBefore Returns a subset of a string before a specific substring.
    toLowerCase Converts all of the characters of a string to lowercase.
    toUpperCase Converts all of the characters of a string to uppercase.
    trim Removes white spaces from both ends of a string.

    You will find an example that includes several JSTL XML tags here.

The following is a detail presentation of each Function JSTL

  • contains

    The contains function determines whether an input string contains a specified substring.
    The syntax is as follows:
    boolean contains(java.lang.String, java.lang.String)
    Example:
    <c:if test="${fn:contains(theString, searchString)}">
  • containsIgnoreCase

    The containsIgnoreCase function is the same as contains function, but ignores the characters case in the search of the string.
    The syntax is as follows:
    boolean containsIgnoreCase(java.lang.String, java.lang.String)
    Example:
    <c:if test="${fn:containsIgnoreCase(theString, searchString)}">
  • endsWith

    The endsWith determines whether an input string ends with a specified suffix.
    The syntax is as follows:
    boolean endsWith(java.lang.String, java.lang.String)
    Example:
    <c:if test="${fn:endsWith(theString, suffix)}">
  • escapeXml

    The escapeXml descapes characters that can be interpreted as XML markup.
    The syntax is as follows:
    boolean escapeXml(java.lang.String)
    Example:
    <c:out="${fn:escapeXml(xmlContainingText)}">
  • indexOf

    The indexOf returns the index within a string of the first occurrence of a specified substring.
    The syntax is as follows:
    int indexOf(java.lang.String, java.lang.String)
    Example:
    <c:out value="${fn:indexOf(theString, searchString)}">
  • join

    The join joins all elements of an array into a string and returns that string.
    The syntax is as follows:
    java.lang.String join (java.lang.String[], java.lang.String)
    Example:
    <c:out value='${fn:join(arrayOfNames, " & ")}' />
  • length

    The length returns the string length or the number of items in a collection or the number of characters in a string.
    The syntax is as follows:
    int length(java.lang.Object)
    Example:
    <c:out value='${fn:length(arrayOfNames)}' />
  • replace

    The replace Returns a string resulting from replacing in an input string all occurrences of a "before" string into an "after" substring..
    The syntax is as follows:
    java.lang.String replace(java.lang.String, java.lang.String, java.lang.String)
    Example:
    <!--  replaces all & with | char. in the string names -->
    <c:out value='${fn:replace(names,"&","|")}' /> 
  • split

    The split returns a string into an array of substrings.
    The syntax is as follows:
    java.lang.String[] split(java.lang.String, java.lang.String)
    Example:
    <c:set value='${fn:split(participant,"&")}' var="arrayOfparticipant"/>
  • startsWith

    The startsWith tests if an input string starts with the specified prefix.
    The syntax is as follows:
    boolean startsWith(java.lang.String, java.lang.String)
    Example:
    <c:if test="${fn:startsWith(product.id, "100-")}">
  • substring

    The substring returns a subset of a string.
    The syntax is as follows:
    java.lang.String substring(java.lang.String, int, int)
    Example:
    P.O. Box: ${fn:substring(zip, beginIndex, endIndex)}
  • substringAfter

    The substringAfter returns a subset of a string following a specific substring.
    The syntax is as follows:
    java.lang.String substringAfter(java.lang.String, java.lang.String)
    Example:
    End of address: ${fn:substringAfter(Address, afterString)}
  • substringBefore

    The substringBefore returns a subset of a string before a specific substring.
    The syntax is as follows:
    java.lang.String substringBefore(java.lang.String, java.lang.String)
    Example:
    Start of address: ${fn:substringBefore(Address, beforeString)}
  • toLowerCase

    The toLowerCase converts all of the characters of a string to lower case and returns it.
    The syntax is as follows:
    java.lang.String toLowerCase(java.lang.String)
    Example:
    All char. to lower case: ${fn:toLowerCase(theString)}
  • toUpperCase

    The toUpperCase converts all of the characters of a string to upper case and returns it.
    The syntax is as follows:
    java.lang.String toUpperCase(java.lang.String)
    Example:
    All char. to upper case: ${fn:toUpperCase(theString)}
  • trim

    The trim removes white spaces from both ends of a string.
    The syntax is as follows:
    java.lang.String trim(java.lang.String)
    Example:
    String is trimmed: ${fn:trim(theString)}

Example of using JSTL functions.

In the example we use Netbeans IDE and Glassfish Server.

You can download this example here (needed tools can be found in the right menu on this page).

If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is FunctionJSTL).

In this example, we will add two files, header.jsp and footer.jsp.

  • It is customary to place all include files, which are used several times in the WEB-INF folder. Some would also like the include files should have the extension .jspf, but this is not a requirement.
    Here is the file we want to include at the top of all pages:
    <h1>JSTL Function demo</h1>
    <hr>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Header.jsp and folder should be WEB-INF).

    Here is the file we want to include at the bottom of all pages:
    <hr>
    Status on <%= (new java.util.Date()).toString() %>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Footer.jsp and folder should be WEB-INF).

We need a JSP file(s) to demonstrate how we use the JSTL functions.

  • Here is the main JSP file:
    <%@ page language="java" contentType="text/html; charset=UTF-8"
             pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <!DOCTYPE html>
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSTL SQL demo</title>
        <style>
          .gradientdown {
            background:  #e0e6ff;
            background: -webkit-linear-gradient(top, #e0e6ff 0%,#eeeeee 100%); /* Chrome10+,Safari5.1+ */
            background: -o-linear-gradient(#e0e6ff, #eeeeee); /* For Opera 11.1 to 12.0 */
            background: -moz-linear-gradient(top, #e0e6ff, #eeeeee); /* For Firefox 3.6 to 15 */
            background: linear-gradient(top, #e0e6ff 0%,#eeeeee 100%); /* W3C Standard syntax (must be last) */
            font-weight: bold;
          }
          table tr.data:nth-of-type(odd) { 
            background: #eeeeee; 
          }
          td {
            vertical-align: top;
          }
          h1 {
            color: blue;
            font-size: 22px;
            margin:  16px 0px 0px 0px;
          }      
          h2 {
            color: blue;
            font-size: 18px;
            margin:  16px 0px 0px 0px;
          }
          h3 {
            color: green;
            font-size: 16px;
            margin: 0px 0px 0px 0px;
          }
          div >span {
            color: blue;
          }
        </style>
      </head>
      <%
        String array[] = {"George", "Ruth", "James", "Ricard", "Obama", "Donald"};
        pageContext.setAttribute("names", array);
      %>
      <body>
        <div style="width:560px; margin-left: 40px;  padding: 10px;">
          <c:import url="/WEB-INF/header.jsp" />
          <h2><fn:join> Function Demo</h2>
          <c:set value='${fn:join(names, " & ")}' var="participant" />
          <p> Participants in this course are "${participant}".</p>
          <h2><fn:contains> Function Demo</h2>
          <c:choose>
            <c:when test="${fn:contains(participant, \"ruth\")}">
              <p> ruth is in this course.</p>
            </c:when>
            <c:otherwise>
              <p> Cannot find "ruth" in this course (tips - use <i>ignore case</i> in the search).</p>
            </c:otherwise>
          </c:choose>
          <h2><fn:containsIgnoreCase> Function Demo</h2>
          <c:if test="${fn:containsIgnoreCase(participant, \"ruth\")}">
            <p> Search for "ruth" and found Ruth when we are using ignore case in the search.</p>
          </c:if>
          <h2><fn:endsWith> Function Demo</h2>
          <c:if test="${fn:endsWith(participant, \"Donald\")}">
            <p> Yes the string ends with "Donald".</p>
          </c:if>   
          <h2><fn:escapeXml> Function Demo</h2>
          <c:set value='Each participant has an unic id</i>.' var="unic" />
          <p>Using escapeXml:  ${fn:escapeXml(unic)}<br>
            NOT Using escapeXml:  ${unic}</p>
          <h2><fn:indexOf> Function Demo</h2>
          <p>The index position of "Donald" in the string is: ${fn:indexOf(participant,"Donald")}.</p>  
          <h2><fn:length> Function Demo</h2>
          <p>There are ${fn:length(names)} participants  in this course.</p>
          <h2><fn:replace> Function Demo</h2>
          <p>Replace & with | sign: ${fn:replace(participant,"&","|")}.</p>
          <h2><fn:split> Function Demo</h2>
          <c:set value='${fn:split(participant,"&")}' var="arrayOfparticipant"/>
          <p>Split participant into an array with & :<br>
            <c:forEach var="part" items="${arrayOfparticipant}">
              [${part}] 
            </c:forEach>
          </p>
          <h2><fn:startsWith> Function Demo</h2>
          <c:if test="${fn:startsWith(participant, \"George\")}">
            <p> Yes the string starts with "George".</p>
          </c:if>
          <h2><fn:substring> Function Demo</h2>
          <p>Here is the 11 first characters of the string:<br>${fn:substring(participant,0,11)}.</p>
          <h2><fn:substringAfter> Function Demo</h2>
          <p>Here is the string after "Ruth":<br>${fn:substringAfter(participant,"Ruth")}.</p>
          <h2><fn:substringBefore> Function Demo</h2>
          <p>Here is the string before "Ruth" + "Ruth":<br>${fn:substringBefore(participant,"Ruth")}Ruth.</p>
          <h2><fn:toLowerCase> Function Demo</h2>
          <p>Converts the string to lower case:<br>${fn:toLowerCase(participant)}.</p>
          <h2><fn:toUpperCase> Function Demo</h2>
          <p>Converts the string to upper case:<br>${fn:toUpperCase(participant)}.</p>
          <h2><fn:trim> Function Demo</h2>
          <c:set value='       Each participant has an unic id</i>.      ' var="untrimmed" />
          <p>Before trim: "${untrimmed}"<br>
            After trim: "${fn:trim(untrimmed)}"
          </p>
          <c:import url="/WEB-INF/footer.jsp" />      
        </div>
      </body>
    </html>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is index).

Creating Deployment descriptor.

  • To run this JSP you have to deploy it to a web-server or a Application server. To deploy means to install the JSP with some instruction to a such server.
  • The instructions are mainly defined to be deployment descriptors. The standard part of the deployment descriptor should be in an XML-file with the name web.xml.

    You may need to create a Deployment descriptor file, web.xml in Netbeans.

  • The contents of the web.xml file should look like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
     http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
      <servlet>
        <servlet-name>FunctionJSP</servlet-name>
        <jsp-file>/index.jsp</jsp-file>
      </servlet>
      <servlet-mapping>
        <servlet-name>FunctionJSP</servlet-name>
        <url-pattern>/FunctionJSP</url-pattern>
      </servlet-mapping>
      <session-config>
        <session-timeout>
          30
        </session-timeout>
      </session-config>
      <welcome-file-list>
        <welcome-file>FunctionJSP</welcome-file>
      </welcome-file-list>
    </web-app>
  • This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app. Every ting inside the last tag is to tell the server about our application, which in this case is a JSP file.
  • With a servlet tag we give the JSP file a servlet name, which is used in the servlet-mapping tag to specify a url for the JSP file.
  • In this way we can have many urls for the same JSP file.
  • If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
  • The welcome-file tag specifies the startup for our application, which in this case and our application is the welcome file with url FunctionJSP. Reorganize the welcome-file-list to what is shown above.

Creating Web-server Deployment descriptor.

  • The context-root (in example /FunctionJSTL) for the application will in most cases be specified by a server vendor deployment descriptor.

    For those who participate in the review: create a Glassfish deployment descriptor in Netbeans.

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, 
    Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN" 
    "http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd">
    <sun-web-app error-url="">
      <context-root>/FunctionJSTL</context-root>
      <class-loader delegate="true"/>
      <jsp-config>
        <property name="keepgenerated" value="true">
          <description>
            Keep a copy of the generated servlet class' java code.
          </description>
        </property>
      </jsp-config>
    </sun-web-app>

Run the application.

  • For those who participate in the review: right click the Web-project and select Run.
  • This results in that the application will be deployed to the server and started.
  • The browser will display:
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.