Interview Questions

JSTL (JSP Standard Tag Library) Core Tags

What is JSTL?
JSTL is a library of tags which can be used in a JSP. The tags provide common functionality such as iterating through elements, displaying values, checking conditions, manipulating XML documents, database access tags etc.,

There are four groups of tags in JSTL
1. Core tags
2. I18N formatting tags
3. XML processing tags
4. DB Access tags

We will look in to the core tags in this article.

To use the JSTL tags in your JSP file, you need to include the tag library as follows.

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/ea/core" %>

The above declaration statement will allow the use of core tags in the JSP. By convention the prefix used is “c”.

To display the value of a scoped variable in JSP use the following tag.

<c:out value=”${title}/>

The above tag prints out the value of “title” variable. A default attribute can also be used if there is a chance that the value of “title” may be null.

<c:out value=”${title}default=”techdive” />

Now let's see how to process a list of elements in JSP.

String[] progLanguage= {“C”,”C++”,”Java”,”C Sharp”,”Perl”,”Ruby”,Small Talk};
request.setAttribute(“progLanguageLst”, progLanguage);

  <c:forEach var=" langValue " items="${ progLanguageLst }"  varStatus=”langStatus”>

        ${ langStatus.count} . <c:out value="${ langValue }" />
       
    </c:forEach>

The above code iterates through the array progLanguage and displays the list of elements using the “c:foreach” tag. The varStatus attribute is used to keep track of the count of the elements processed in the list. The output will be as follows

Output :

1.      C
2.      C++
3.      Java
4.      C Sharp
5.      Perl
6.      Ruby
7.      Small Talk

To set a variable to a particular scope use the following tag.

<c:set  var=”level”  scope=”session”  value=”Admin” />

The above code sets the value “Admin” to the “level” variable in session scope.
To check for conditions use the “c:if” tag.

<c:if  test=”${level==’Admin’}>
// Show all the tabs to user.
</c:if>

<c:if  test=”${level==’Normal’}>
// Show only minimal tabs to user.
</c:if>

What if all conditions are false and you need an else part? It can be done using “c:choose” tag.

<c:choose>
    <c:when  test=”${level==’Admin’}>
        // Show all the tabs to user.
    </c:when>

    <c:when  test=”${level==’Super’}>
        // Show all tabs except admin related tabs.
    </c:when>

    <c:otherwise >
        // Show only minimal tabs to user.
    </c:otherwise>
</c:choose>

In this way we can use JSTL core tags for simple operations in a JSP.