JSTL-根据条件设置背景颜色

JSTL- set background color with condition

我是 Java、JSTL、CSS、JSP...任何 Java 相关和 Web 应用程序领域的新手。 我正在学习并同时制作自己的网络程序(使用 Spring MVC)。

现在我将在 .jsp 文件中使用 JSTL 按条件设置 2 种不同的背景颜色。 我的条件是中位数。所以 jsp 文件中带有 jstl 的逻辑应该是这样的:

if (value < median)  
// set background: green
else
// set background: red

我已经在 Controller 中完成了所有的中值计算。 所以我的控制器提供中位数 以及整数类型和字符串类型的数据

(我注意到整数类型的数据不能在浏览器页面上显示,对吗?[Q1]

因此整数类型用于带中位数的条件运算,字符串类型用于在浏览器上呈现)

model.addAttribute("dataNo", dataNo);
model.addAttribute("dataStr", dataStr);
model.addAttribute("dataInt", dataInt);
model.addAttribute("median", median);

我的。 jsp 像这样

(我的 table 正在增加列)

<table class="table table-bordered">
    <tbody>
        <tr>
            <c:forEach var="dataNoValue" items="${dataNo}">
                <th>${dataNoValue}</th>
            </c:forEach>

        </tr>
        <tr>
            <c:forEach var="dataStrValue" items="${dataStr}">
                <th class="${dataInt < median ? 'background-color: green':'background-color: red'}">${dataStrValue}</th> -- [Q2] 
            </c:forEach>
        </tr>
    </tbody>
</table>

是的,[Q2]是错误的,有什么建议吗?赞赏!

您应该将 class 属性替换为样式属性,如下所示:

<th style="${dataInt < median ? 'background-color: green':'background-color: red'}">${dataStrValue}</th>

或者创建两个 classes 绿色和红色并像这样使用它们:

<style>
 .green{background-color: green}
 .red{background-color: red}
</style>

<th class="${dataInt < median ? 'green':'red'}">${dataStrValue}</th>