如何根据Student类的布尔值在JSP的VIP列输出Yes/No字符串
解决方案:在JSP中将布尔值转换为"Yes/No"显示
你只需要对JSP页面中VIP列的代码做简单修改,就能实现把goldCustomer的布尔值转换成"Yes"或"No"显示,这里有两种常用的方法:
方法1:使用JSTL的<c:if>条件标签
利用<c:if>标签判断goldCustomer的值,分别输出对应的文本。修改你JSP里的VIP列代码:
<td> <c:if test="${data.goldCustomer}">Yes</c:if> <c:if test="${!data.goldCustomer}">No</c:if> </td>
方法2:使用EL表达式的三目运算符(更简洁)
EL支持类似Java的三目运算符,一行代码就能搞定转换:
<td>${data.goldCustomer ? 'Yes' : 'No'}</td>
修改后的完整JSP代码
下面是替换后的完整JSP代码,你可以直接参考使用:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ page import="java.util.* , com.jsptag.demo.Student" %> <% List<Student> students = new ArrayList<>(); students.add(new Student("Rahul" , "Rawat" , false)); students.add(new Student("Rohit" , "Negi" , true)); students.add(new Student("Mahesh" , "Gupta" , false)); pageContext.setAttribute("myStudents", students); %> <html> <body> <table border="1"> <tr> <th>First Name</th> <th>Last Name</th> <th>VIP ?</th> </tr> <c:forEach var="data" items="${myStudents}"> <tr> <td>${data.firstName}</td> <td>${data.lastName}</td> <!-- 这里用三目运算符实现布尔值转文本 --> <td>${data.goldCustomer ? 'Yes' : 'No'}</td> </tr> </c:forEach> </table> </body> </html>
补充说明
之所以原来直接显示true/false,是因为EL表达式${data.goldCustomer}会自动调用你的isGoldCustomer()方法,返回的布尔值会直接被输出成字符串。通过上面的条件判断或三目运算符,就能把布尔值映射成你需要的友好文本啦。
内容的提问来源于stack exchange,提问作者Anshul Rawat
相关产品推荐
相关产品推荐

