问题:在action中将从数据库中查出的数据的集合在JSP页面循环打印出来?
为了举例简单,这里我直接在action中设置一个ArrayList集合,然后放到HttpServletRequest对象中供前台JSP页面获取,代码如下:
List<String> mathList = new ArrayList<String>(); mathList.add("高等数学"); mathList.add("离散数学"); mathList.add("线性代数"); mathList.add("概率论与数理统计"); mathList.add("数字逻辑"); mathList.add("数值分析"); mathList.add("运筹学"); ServletActionContext.getRequest().setAttribute("test", mathList);
在JSP页面中循环打印,用s标签和c标签分别是这样的:
<s:iterator var="temp" value="#request.test"> <s:property value="#temp" /> </s:iterator> <br><hr> <c:forEach items="${requestScope.test }" var="temp"> <c:out value="${temp }"></c:out> </c:forEach> <br><hr>
可以发现:s标签通过 “#request.test“这种形式获取request对象,而c标签则通过EL隐式对象 “${requestScope.test }”(PS:不熟悉的话可以参考这篇文章:http://www.zifangsky.cn/2016/02/jsp中的el隐式对象/)来获取request对象;其次,<s:property value=”#temp” />里的value值只能是一个变量,不能直接输出一段文字,而<c:out value=”${temp }”></c:out>不仅可以通过EL表达式输出变量,而且可以直接输出一段文字
其他的一些测试代码:
<s:iterator var="temp0" value="{‘1‘,‘2‘,‘3‘}"> <s:property value="temp0" /> </s:iterator> <br><hr> <s:iterator value="{‘java se‘,‘java web‘,‘java me‘,‘java ee‘}" var="name" status="status"> <s:if test="#request.test != null"> <s:property value="name" /> </s:if> </s:iterator> <br><hr> <c:if test="${empty requestScope.test}"> <c:out value="c empty"></c:out> </c:if> <c:if test="${!empty requestScope.test}"> <c:out value="c not empty"></c:out> </c:if>
以上代码的完整输出:
本文出自 “zifangsky的个人博客” 博客,请务必保留此出处http://983836259.blog.51cto.com/7311475/1741855
原文:http://983836259.blog.51cto.com/7311475/1741855