💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
本节中,我们将性别显示为男或女。这里有两种方法供我们选择。 # 方法一:使用标签 /jsp/teacher/index.jsp ``` <s:iterator value="teachers" var="teacher"> <tr> <td>1</td> <!-- property输出变量 teacher为内部变量,前面加入# --> <td><s:property value="#teacher.name" /></td> <td><s:property value="#teacher.username" /></td> <!-- 使用if来判断真与假,适用于非真即假的值 --> <td><s:if test="#teacher.sex">男</s:if> <s:else>女</s:else></td> <td><s:property value="#teacher.email" /></td> </tr> </s:iterator> ``` 上面,我们使用if else标签来输出性别。 # 方法二:使用M层 增加获取属性代码 ``` package entity; ... // 声明主体 @Entity public class Teacher { ... // 输出性别 public String getSexAttr() { if (sex) { return "0男"; } else { return "1女"; } } ... } ``` V层: ``` <td><s:property value="#teacher.sexAttr" /></td> ``` # 测试 TODO: # 输出序号 顺便,我们一并输出一样序号吧。 我们刚刚学过了`iterator`这个标签的两个属性,分别是数据源`value`和用于循环输出的`teacher`,这次我们再学用于显示状态的`status`. ``` <s:iterator value="teachers" var="teacher" status="status"> <tr> <td><s:property value="#status" /></td> <!-- property输出变量 teacher为内部变量,前面加入# --> <td><s:property value="#teacher.name" /></td> <td><s:property value="#teacher.username" /></td> <td><s:property value="#teacher.sexAttr" /></td> <td><s:property value="#teacher.email" /></td> </tr> </s:iterator> ``` 我们直接输出`status`,发现它的类型为`IteratorStatus`。我们再以它为关键字到官方上去查一下这个类型。 > 官网:[https://struts.apache.org/docs/](https://struts.apache.org/docs/) 找到它的文档说明页面:[https://struts.apache.org/maven/struts2-core/apidocs/org/apache/struts2/views/jsp/IteratorStatus.html](https://struts.apache.org/maven/struts2-core/apidocs/org/apache/struts2/views/jsp/IteratorStatus.html) 介绍如下: ``` The iterator tag can export an IteratorStatus object so that one can get information about the status of the iteration, such as: index: current iteration index, starts on 0 and increments in one on every iteration count: iterations so far, starts on 1. count is always index + 1 first: true if index == 0 even: true if (index + 1) % 2 == 0 last: true if current iteration is the last iteration odd: true if (index + 1) % 2 == 1 ``` 在这,我们使用count来输出它的序列: ``` <s:iterator value="teachers" var="teacher" status="status"> <tr> <td><s:property value="#status.count" /></td> <!-- property输出变量 teacher为内部变量,前面加入# --> <td><s:property value="#teacher.name" /></td> <td><s:property value="#teacher.username" /></td> <td><s:property value="#teacher.sexAttr" /></td> <td><s:property value="#teacher.email" /></td> </tr> </s:iterator> ``` ## 测试 的确,序号就这么来了 :)。 **做为初学者的我们,所遇到的问题,别人早就遇到并解决掉了。**我们要做的,就是去找它的解决方法。如果你没有找到相关的问题和答案,有以下几种能: 1. 你使用的是百度。 2. 你搜索的关键字错了。 3. 你的思想出现偏差,走到了本来就不存在死胡同。 # 作业 试试status的其它的几个属性 # 总结: 使用标签是在前台对性别进行转换,使用M层增加`getSexAttr()`方法,是在后台进行转换。方式不同,但实现的原理相同。 在实际的开发中,非0即1的值,我们将采用Boolean类型,并使用第一方法,即标签法来实现文本的输出。