[英]What is the model of using Smook and Freemarker to transform Java Objects to XML?
[英]Using Freemarker to display a table of arbitrary Java objects and their fields
首先,我已經閱讀了這個問題 ,但是並沒有解決我的問題。
我正在嘗試創建一個表,該表將顯示Java對象的任意列表。 當我說“任意”時,我的意思是對象的數量是任意的,並且對象的類型是任意的(盡管它們都將是同一類的實例)。 我希望該表的行代表對象,而列則代表每個對象的實例變量(基本上是電子表格樣式)的值。 但是,第一行將只是實例變量名稱的列表。
我目前正在測試的對象的所有變量都設置為private,但是我提供了相關的getter和setter。
這是我的Java代碼的摘錄。 我正在從Oracle Coherence緩存中提取對象,並將其放入ArrayList中。 然后,我創建一個實例變量名稱的字符串數組:
/**
* Get objects in cache and add to ArrayList.
*/
for(Iterator iter = currentCache.entrySet().iterator();iter.hasNext();){
Map.Entry entry = (Map.Entry)iter.next();
String key = (String) entry.getKey();
Pof tempPof = (Pof)entry.getValue();
tableList.add(tempPof);
System.out.println("one loop");
}
request.setAttribute("beans",tableList);
System.out.println("Size of tableList is: " + tableList.size());
/**
* Build an array containing the variable names of cached objects.
*/
Field[] fields = Pof.class.getDeclaredFields();
String[] variableNames = new String[fields.length];
for(int j = 0; j < fields.length;j++){
variableNames[j] = fields[j].getName();
System.out.println(variableNames[j]);
}
request.setAttribute("colNames",variableNames);
/**
* numCols determines the number of columns displayed in the table.
*/
int numCols = fields.length;
String[] fieldStrings = new String[numCols];
request.setAttribute("numCols",numCols);
Pof thing = (Pof) tableList.get(0);
以下是相關.ftl文件的摘錄:
<table border = "1px">
<thead>
<tr>
<th colspan="${numCols}">${selectedCache}</th>
</tr>
<tr>
<#list colNames as colName>
<td>${colName}</td>
</#list>
</tr>
</thead>
<tbody>
<#list beans as bean>
<tr>
<#list colNames as colName>
<td>${bean[colName]}</td>
</#list>
</tr>
</#list>
</tbody>
</table>
這使我出現以下錯誤:
freemarker.core.InvalidReferenceException:以下內容評估為空或丟失:==> bean [colName] [在模板“ front.ftl”的第46行第35列中]
提示:導致此錯誤的是[[]最后一步,而不是之前的錯誤。
提示:如果已知失敗的表達式合法地引用了有時為空或缺失的內容,請指定默認值,例如myOptionalVar!myDefault,或使用<#if myOptionalVar ??> when-present <#else> when-missing。 (這些僅覆蓋表達式的最后一步;要覆蓋整個表達式,請使用括號:(myOptionalVar.foo)!myDefault,(myOptionalVar.foo)?? FTL堆棧跟蹤(“〜”表示與嵌套相關):-失敗位於:$ {bean [colName]} [在第46行第33列的模板“ front.ftl”中]
at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:134)
at freemarker.core.EvalUtil.coerceModelToTextualCommon(EvalUtil.java:451)
at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:374)
at freemarker.core.DollarVariable.calculateInterpolatedStringOrMarkup(DollarVariable.java:96)
at freemarker.core.DollarVariable.accept(DollarVariable.java:59)
Truncated. see log file for complete stacktrace
問題似乎出在我的ftl語法上。 也就是說,它不喜歡表達式$ {bean [colName]}。
問題:
1)語法錯誤嗎?
2)這是Freemarker無法做的事情嗎?
3)我應該嘗試其他方法嗎? 例如,是否應該僅創建一個包含每個實例變量值數組(或其他數據結構)的存儲桶的數組?
它應該工作,並提供:
Pof
是公共類 colName
"foo"
都有一個公共的Pof.getFoo()
方法。 getFoo()
返回非null
值。 如果有時返回null
,則必須指定顯示的內容,例如: ${bean[colName]!'-'}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.