[英]jstl core for Each over heterogeneous collection
我有一個控制器返回JSP頁面一個MyClass
類型的ArrayList
類型的對象。 ArrayList內部的對象屬於不同的類,比如說MyClass1
和MyClass2
,它們每個都擴展了MyClass。 我可以使用forEach標記遍歷集合,並由於MyClass
的字段type
而獲得當前元素type
,但是當我嘗試訪問MyClass1
的特定字段時,出現此錯誤。
javax.el.PropertyNotFoundException: Property 'noContentMessage' not found on type it.sei.core.rinterface.MyClass1
。
這是我的代碼:
class MyClass {
String type;
String variable;
}
class MyClass1 extends MyClass{
String someOtherField;
}
class MyClass2 extends MyClass{
String noContentMessage;
}
<core:forEach items="${model.GraphList}" var="element" varStatus="index">
<script language="javascript" type="text/javascript">
var type = '${element.type}';
switch (type)
{
case "type1":
{
var variable = '${element.variable}';
}
break;
case "type2":
{
var message = '${element.noContentMessage}';
}
break;
}
</script>
</core:forEach>
那么為什么會這樣呢? JSTL無法處理這種情況嗎?
JSP EL從不訪問字段。 只有財產,即公共吸氣劑。
為要從JSP EL使用的字段添加一個公共獲取器:
public String getNoContentMessage() {
return this.noContentMessage;
}
編輯:
同樣,您的switch塊是JavaScript代碼,在頁面生成后很長時間就在客戶端執行。 對於JSP引擎,JavaScript代碼是純文本,並且將生成switch塊的所有分支。 因此,對於集合中的每個對象,將評估所有JSP EL表達式。
該代碼應重寫為
<script language="javascript" type="text/javascript">
var type = '${element.type}'; // is it necessary?
<c:if test="${element.type == 'type1'}">
var variable = '${element.variable}';
</c:if>
<c:if test="${element.type == 'type2'}">
var message = '${element.noContentMessage}';
</c:if>
</script>
盡管我不明白為集合中的每個元素一次又一次重新定義相同的JS變量的意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.