You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JSP中动态使用JavaScript循环变量及表达式标签多循环变量

Hey there! Let's tackle your two questions about JSP and JavaScript—these are really common scenarios when building dynamic web pages, so I’ll walk you through practical, actionable examples for each.

1. Using JavaScript Loop Variables for Dynamic Effects in JSP

First, it’s important to remember: JSP runs on the server to generate HTML/JS, and JavaScript runs in the browser after the page loads. So we usually pass server-side data to JS first, then use JS loops to create dynamic behavior.

Example 1: Pass Server-Side Data to JS, Then Loop for Dynamic DOM

Here we’ll use a Java List in JSP, convert it to a JavaScript array, then loop through that array to create interactive elements:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.List, java.util.ArrayList, java.util.Map, java.util.HashMap, com.google.gson.Gson" %>
<!DOCTYPE html>
<html>
<head>
    <title>Dynamic JS Effects</title>
    <script>
        window.onload = function() {
            // Receive data from JSP (converted to a JS array via Gson)
            const productList = <%= new Gson().toJson(request.getAttribute("products")) %>;
            
            const container = document.getElementById("product-container");
            
            // JS loop to create dynamic cards with click effects
            productList.forEach((product, index) => {
                const card = document.createElement("div");
                card.className = "product-card";
                card.innerHTML = `
                    <h4>${index + 1}. ${product.name}</h4>
                    <p>Price: $${product.price}</p>
                `;
                
                // Dynamic click effect: toggle background color
                card.addEventListener("click", () => {
                    card.style.backgroundColor = card.style.backgroundColor === "#f5f5f5" ? "#ffffff" : "#f5f5f5";
                    alert(`You selected ${product.name}!`);
                });
                
                container.appendChild(card);
            });
        };
    </script>
    <style>
        .product-card { padding: 12px; margin: 8px; border: 1px solid #ddd; cursor: pointer; border-radius: 4px; }
    </style>
</head>
<body>
    <h2>Our Products</h2>
    <div id="product-container"></div>

    <%-- Server-side code to populate product data --%>
    <%
        List<Map<String, Object>> products = new ArrayList<>();
        
        Map<String, Object> laptop = new HashMap<>();
        laptop.put("name", "Ultrabook Pro");
        laptop.put("price", 1299.99);
        products.add(laptop);
        
        Map<String, Object> phone = new HashMap<>();
        phone.put("name", "Mobile X");
        phone.put("price", 799.99);
        products.add(phone);
        
        request.setAttribute("products", products);
    %>
</body>
</html>

Note: We use Gson here to safely convert Java objects to JS syntax—avoid manually stringifying data, as it can lead to syntax errors or XSS risks. Make sure your project includes the Gson dependency.

Example 2: JSP Loop to Populate JS Variables

You can also use a JSP loop to directly inject values into a JavaScript array, then use that array for dynamic effects:

<script>
    const categoryColors = [];
    <% 
        String[] categories = {"Electronics", "Clothing", "Home Goods"};
        String[] colors = {"#2196F3", "#4CAF50", "#FF9800"};
        
        for (int i = 0; i < categories.length; i++) {
    %>
        categoryColors.push({category: "<%= categories[i] %>", color: "<%= colors[i] %>"});
    <% } %>
    
    // JS loop to apply dynamic styles to category headers
    categoryColors.forEach((item) => {
        const header = document.getElementById(`cat-${item.category.toLowerCase().replace(' ', '')}`);
        header.style.color = item.color;
        header.addEventListener("mouseover", () => {
            header.style.textDecoration = "underline";
        });
        header.addEventListener("mouseout", () => {
            header.style.textDecoration = "none";
        });
    });
</script>

<h3 id="cat-electronics">Electronics</h3>
<h3 id="cat-clothing">Clothing</h3>
<h3 id="cat-homegoods">Home Goods</h3>
2. Using Multiple Loop Variables in JSP Expression Tags

JSP expression tags (<%= %>) output the value of a Java expression. To use multiple loop variables, you’ll typically define them inside a JSP scriptlet loop (<% for (...) { %>) and reference them in expressions.

Example 1: Single Loop with Multiple Associated Variables

Here we loop through three parallel arrays, using an index to access corresponding values from each:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.Arrays" %>
<!DOCTYPE html>
<html>
<body>
    <h2>Product Inventory</h2>
    <table border="1" cellpadding="8">
        <tr>
            <th>Product</th>
            <th>Price</th>
            <th>Stock</th>
            <th>Status</th>
        </tr>
        <%
            String[] names = {"Laptop", "Smartphone", "Tablet"};
            double[] prices = {999.99, 699.99, 499.99};
            int[] stockCounts = {10, 25, 8};
            
            for (int i = 0; i < names.length; i++) {
                String name = names[i];
                double price = prices[i];
                int stock = stockCounts[i];
        %>
            <tr>
                <td><%= name %></td>
                <td>$<%= price %></td>
                <td><%= stock %></td>
                <td>
                    <%-- Use multiple variables to determine status --%>
                    <% if (stock < 10 && price > 500) { %>
                        <span style="color: red; font-weight: bold;">Low Stock & High Value</span>
                    <% } else if (stock < 10) { %>
                        <span style="color: orange;">Low Stock</span>
                    <% } else { %>
                        <span style="color: green;">In Stock</span>
                    <% } %>
                </td>
            </tr>
        <% } %>
    </table>
</body>
</html>

Example 2: Nested Loops with Multiple Variables

For nested loops, you’ll have outer and inner loop variables that you can use together in expressions:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
    <h2>Multiplication Table</h2>
    <table border="1" cellpadding="5">
        <% for (int row = 1; row <= 10; row++) { %>
            <tr>
                <% for (int col = 1; col <= 10; col++) { %>
                    <td>
                        <%= row %> × <%= col %> = <%= row * col %>
                    </td>
                <% } %>
            </tr>
        <% } %>
    </table>
</body>
</html>

Bonus: Use JSTL for Cleaner Multiple Variable Loops

If you prefer to avoid scriptlets, JSTL’s <c:forEach> tag lets you use varStatus to get loop indices, which you can use to access parallel collections:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<body>
    <h2>JSTL Loop with Multiple Variables</h2>
    <c:set var="productNames" value="${['Headphones', 'Keyboard', 'Mouse']}" />
    <c:set var="productPrices" value="${[149.99, 89.99, 49.99]}" />
    
    <ul>
        <c:forEach items="${productNames}" var="name" varStatus="loopStatus">
            <li>
                ${loopStatus.index + 1}. ${name} - $${productPrices[loopStatus.index]}
            </li>
        </c:forEach>
    </ul>
</body>
</html>

To wrap up: Always keep server-side (JSP) and client-side (JS) execution timings in mind. For multiple loop variables in JSP, either use scriptlet loops with parallel variables or leverage JSTL for cleaner, more maintainable code.

内容的提问来源于stack exchange,提问作者Abdul Quadir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:20:01