[go: up one dir, main page]

Enterprise Java

JSTL forEach Index Values Example

JSTL is a powerful tool for simplifying Java-based web applications, particularly when working with dynamic data in JSP pages. One of the most common use cases involves iterating over lists of data with the <c:forEach> loop. But what if you need to capture the index of each element for use in JavaScript or other logic? This article will show you how to easily retrieve and utilize JSTL forEach index values to enhance your web application’s interactivity and functionality.

1. Project Setup

We will create a basic Jakarta EE web application where we have a list of categories. These categories will be set as an attribute in the HttpServletRequest, and we will use JSTL to display them in an HTML list. The key point here is to pass the index of each category to a JavaScript function using the <c:forEach> loop and the varStatus attribute.

2. Creating the Servlet

First, let’s create a simple servlet that sets a list of categories in the request attribute. These categories will be passed to the JSP page for iteration.

@WebServlet(name = "CategoryServlet", urlPatterns = {"/categories"})
public class CategoryServlet extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Simulating the categories list (in a real application, this could come from a database)
        String[] categoriesList = {"Technology", "Health", "Finance", "Education"};

        // Setting categories list in the request attribute
        request.setAttribute("categoriesList", categoriesList);

        // Forwarding the request to the JSP page
        RequestDispatcher dispatcher = request.getRequestDispatcher("/categories.jsp");
        dispatcher.forward(request, response);
    }

}

In this example, we have created a CategoryServlet that stores a list of categories in the HttpServletRequest attribute and forwards the request to categories.jsp.

3. JSP Page to Display Categories

Now that we have the categories list in the request, let’s display it in the JSP page using the <c:forEach> loop. We will also pass the index of each category to a JavaScript function.

Here’s how we can do this:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
    <head>
        <title>Categories List</title>
        <script type="text/javascript">
            function getCategoryIndex(index) {
                alert("Category index: " + index);
            }
        </script>
    </head>
    <body>
        <h2>Categories</h2>
        <ul>
            <c:if test="${not empty categoriesList}">
                <c:forEach var="categoryName" items="${categoriesList}" varStatus="loop">
                    <li>
                        <a href="#" onclick="getCategoryIndex(${loop.index})">
                            ${categoryName}
                        </a>
                    </li>
                </c:forEach>
            </c:if>
        </ul>
    </body>
</html>

In this JSP code, we use JSTL’s <c:forEach> tag to iterate through the categoriesList. The varStatus="loop" attribute allows us to access the index of each item in the loop.

Key Components in the Code:

  • var="categoryName": This attribute defines the variable name that will hold the current value of the list element during each iteration.
  • items="${categoriesList}": This binds the list of categories from the request attribute (categoriesList) to the items attribute.
  • varStatus="loop": This allows access to special loop-related properties, such as index, count, and first.
  • ${loop.index}: This outputs the 0-based index of the current element in the loop.

4. Passing the Index to JavaScript

The key point in this example is passing the index value to the JavaScript function getCategoryIndex(). By using the loop.index property, we can retrieve the index of the current category and pass it to the function when a link is clicked.

The onclick attribute in the <a> tag contains ${loop.index}, which dynamically evaluates to the index of the category being rendered. When the user clicks on a category, the JavaScript function is invoked, and the index of the clicked category is passed as an argument.

How varStatus Works in <c:forEach>

The varStatus attribute in JSTL’s <c:forEach> loop provides a convenient way to access loop-related information. This includes the index, whether it is the first or last element, and the total number of items in the loop. Here are some commonly used properties of the varStatus object:

  • index: The current 0-based index of the iteration (used in our example).
  • count: The current 1-based count of the iteration (useful for counting iterations).
  • first: A boolean value indicating whether the current iteration is the first one.
  • last: A boolean value indicating whether the current iteration is the last one.
  • size: The total number of items in the collection.

In the code example above, we used ${loop.index} to get the 0-based index of each element.

When we deploy our application to a servlet container such as Apache Tomcat or Jetty, accessing the /categories URL will trigger the CategoryServlet. This servlet sets the list of categories in the request scope. The categories.jsp page then dynamically renders this list, displaying each category as a clickable link.

If everything is set up correctly, your output will look like:

When a user clicks on any category link, the JavaScript function getCategoryIndex() is triggered, displaying an alert box with the index of the clicked category. For example, clicking the first link (Technology) will display: Category index: 0.

Screenshot showing the output after clicking the Technology link-index 0 in the JSTL forEach index values example.

Clicking the Education link will display (Category index: 3):

Screenshot showing the output after clicking the link Education-index 3 in the JSTL forEach index values example.

5. Conclusion

In this article, we explored how to retrieve the index of each element when using the <c:forEach> loop in JSTL. By leveraging the varStatus attribute, we were able to access the index of each element in the collection and pass it to a JavaScript function. This approach is useful when we need to dynamically interact with elements on the client side based on their index in the iteration.

6. Download the Source Code

This article covered how to retrieve JSTL forEach index values and use them in your applications.

Download
You can download the full source code of this example here: jstl foreach index values

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button