如何在JSP与标签文件间传递属性并复用更新后的值?
解决JSP自定义标签中复用rowCount变量的问题
你的问题根源在于JSP自定义标签的属性传递机制和EL变量的作用域查找规则:
- 当你把
rowCount作为标签属性传入时,它只是值的拷贝,标签内部的属性是局部变量,和外部的rowCount并非同一个引用; - 标签里的
<c:set var="rowCount" ...>默认会在page作用域创建新变量,但EL在标签内部会优先查找标签的属性,导致外部的rowCount根本没被修改。
下面给你两种可行的解决方案:
方案一:直接操作page作用域的变量(最简单)
不用把rowCount作为标签属性传递,让标签直接访问并修改page作用域里的rowCount变量:
外部JSP代码
<%-- 明确声明page作用域的rowCount --%> <c:set var="rowCount" value="0" scope="page" /> <product:attribute attrKey="${msg_site}:" attrValue="${product.site}" /> <product:attribute attrKey="${msg_name}:" attrValue="${product.name}" /> <product:attribute attrKey="${msg_type}:" attrValue="${product.type}" />
自定义标签文件(attribute.tag)
<%@ tag body-content="empty" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%-- 直接使用page作用域的rowCount --%> <c:if test="${pageScope.rowCount >= 2}" > </div> <div class="col-md-12 col-sm-12 col-xs-12 "> <c:set var="rowCount" value="0" scope="page" /> </c:if> <%-- 更新page作用域的rowCount --%> <c:set var="rowCount" value="${pageScope.rowCount + 1}" scope="page" /> <%-- 这里添加你原本的标签内容,比如渲染属性键值对 --%> <div class="attribute-item"> <span>${attrKey}</span> <span>${attrValue}</span> </div>
这样每次标签都会直接修改page作用域的rowCount,后续标签调用时就能拿到更新后的值。
方案二:传递变量名实现动态修改(更灵活)
如果需要支持不同的计数器变量名,可以传递变量的名称而非值,通过EL动态访问作用域变量:
外部JSP代码
<c:set var="rowCount" value="0" /> <product:attribute rowCountVar="rowCount" attrKey="${msg_site}:" attrValue="${product.site}" /> <product:attribute rowCountVar="rowCount" attrKey="${msg_name}:" attrValue="${product.name}" /> <product:attribute rowCountVar="rowCount" attrKey="${msg_type}:" attrValue="${product.type}" />
自定义标签文件(attribute.tag)
<%@ attribute name="rowCountVar" required="true" %> <%@ attribute name="attrKey" required="true" %> <%@ attribute name="attrValue" required="true" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%-- 动态获取当前计数器的值 --%> <c:set var="currentCount" value="${pageScope[rowCountVar]}" /> <c:if test="${currentCount >= 2}" > </div> <div class="col-md-12 col-sm-12 col-xs-12 "> <c:set var="${rowCountVar}" value="0" scope="page" /> </c:if> <%-- 动态更新计数器的值 --%> <c:set var="${rowCountVar}" value="${currentCount + 1}" scope="page" /> <%-- 标签内容渲染 --%> <div class="attribute-item"> <span>${attrKey}</span> <span>${attrValue}</span> </div>
这种方式允许你在不同场景下使用不同的计数器变量,灵活性更高。
内容的提问来源于stack exchange,提问作者Ricardo Machado
相关产品推荐
相关产品推荐

