如何将c:forEach标记的循环索引附加到struts select / text标记的属性?
例如。
<%@ taglib uri="/WEB-INF/tld/struts-html.tld" prefix="html"%>
<c:forEach begin="2" end="${pageView.guestCount}" varStatus="gC">
<div class="section guest-details">
<html:select property='title_guest<c:out value="${gC.index}"/>'>
<html:options collection="titles" property="code" labelProperty="value" />
</html:select>
</div>
</c:forEach>
抛出以下错误
javax.servlet.jsp.JspException at org.apache.struts.taglib.html.SelectTag.calculateMatchValues(SelectTag.java:246)
现在,当我在<html:select ...
调试代码时,它会显示当它设置的属性属性时,其设置为"title_guest<c:out value="${gC.index}"/>"
,这可能是上述异常的原因。
另外,我应该提一下,如果我使用上面的格式将循环索引附加到标准html标记属性(如<select>
标记),则代码可以正常工作。
例如
<c:forEach begin="2" end="${pageView.guestCount}" varStatus="gC">
<div class="section guest-details">
<select name='title_guest<c:out value="${gC.index }"/>'>
<option value="">Select Title</option>
</select>
</div>
</c:forEach>
正确输出预期的HTML
我做错了什么,我应该使用EL来创建填充html:select标签的“property”属性的字符串吗?
更新
还尝试了以下代码段,但也无效
<html:select property="title_guest${gC.index}">
而且,这也不起作用
<c:set var="guestTitle">title_guest${gC.index}</c:set>
<html:select property="${guestTitle}" styleClass="{required: true}">
<html:options collection="titles" property="code" labelProperty="value" />
</html:select>
答案 0 :(得分:8)
但是, c:forEach 会将varStatus变量导出为pageContext属性,该属性可以被检索并用于提取索引/计数。唯一的问题是你必须导入javax.servlet.jsp.jstl.core.LoopTagStatus类并使用它来手动重新创建varStatus变量,以便它可以在scriplet中使用
以下是有效的代码片段
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
import="javax.servlet.jsp.jstl.core.LoopTagStatus"
%>
...
<c:forEach begin="2" end="${pageView.guestCount}" varStatus="gC">
<% LoopTagStatus gN = (LoopTagStatus)pageContext.getAttribute("gC"); %>
<html:select property='<%="title_guest"+gN.getIndex()%>'>
<html:options collection="titles" property="code" labelProperty="value" />
</html:select>
</c:forEach>
我不认为这是一个干净的解决方案(但可能是唯一的解决方案)。因此,在接受最终答案之前,我会先让社群对这个答案进行投票(或写出更好的答案)。
答案 1 :(得分:0)
这将是一个嵌套的表达式,这是不允许的,请尝试使用此代替
<html:select property='title_guest${gC.index}'>
答案 2 :(得分:0)
我的方式
<c:forEach begin="1" end="${page.totalPages}" varStatus="lp">
<li><a href="<c:url value="/course?page=${pageScope.lp.index}"/>">${pageScope.lp.index}</a></li>
</c:forEach>