Show List

JSP standard tag library

The JSP Standard Tag Library (JSTL) is a collection of tag libraries that provide a standard set of tags for common functionality in JSP pages. These tags provide a more elegant way to perform common operations, such as looping through a collection of data, conditional rendering, and formatting data. Here are some examples of how JSTL can be used in JSP pages:

  • Looping through a collection of data:
jsp
Copy code
<c:forEach items="${myList}" var="item"> ${item} </c:forEach>

In this example, the c:forEach tag is used to loop through a collection of data stored in the myList variable. For each item in the list, the var attribute is used to define a variable called item that represents the current item being processed. The body of the tag simply displays the value of the item variable.

  • Conditional rendering:
jsp
Copy code
<c:if test="${isAdmin}"> <p>Welcome, Admin!</p> </c:if> <c:choose> <c:when test="${isMember}"> <p>Welcome, Member!</p> </c:when> <c:otherwise> <p>Welcome, Guest!</p> </c:otherwise> </c:choose>

In this example, the c:if tag is used to conditionally display a message if the user is an admin. The test attribute is used to define the condition to be evaluated. If the condition is true, the body of the tag is rendered, otherwise it is ignored.

The c:choose tag is used to define a switch statement with multiple cases. In this example, the c:when tag is used to test if the user is a member and render a message accordingly. The c:otherwise tag is used to define a default case that is rendered if none of the other cases are matched.

  • Formatting data:
jsp
Copy code
<fmt:formatDate value="${myDate}" pattern="dd/MM/yyyy" />

In this example, the fmt:formatDate tag is used to format a date stored in the myDate variable. The value attribute is used to define the date to be formatted, and the pattern attribute is used to define the format of the date. In this case, the date is formatted as "dd/MM/yyyy".

These are just a few examples of how JSTL can be used in JSP pages. JSTL provides a wide variety of tags for common functionality, such as database access, XML processing, and internationalization. Using JSTL can make JSP pages more concise and easier to maintain.



    Leave a Comment


  • captcha text