动态h:inputtext以支持jsf中的Bean数组[ClassCastException] [英] Dynamic h:inputtext to backing Bean Array in jsf [ClassCastException]
问题描述
我正在使用JSF 2.0 我在将inputTexts的值设置为double表时遇到问题.
I'm using JSF 2.0 I have a problem to set Values of inputTexts to a table of double.
我可以这样做:
<h:inputText value="#{myBean.table[0]}" />
但是,我想像这样循环进行:
But, I would like to do it in a loop like that:
<c:forEach var="i" begin="0" end="#{myBean.inputsNumber}">
<h:inputText value="#{myBean.table[i]}" /> <br/>
</c:forEach>
<h:commandButton action="#{myBean.calculate}" value="Calculate" />
Result: #{myBean.result}
这是我的后援豆:
@ManagedBean
@SessionScoped
public class MyBean {
private double[] table;
private double result;
public MyBean() {
table = new double[100];
}
public void calculate() {
for (int i = 0; i < table.length; i++) {
result += table[i];
}
}
public double[] getTable() {
return table;
}
public int getInputsNumber() {
return table.length;
}
public double getResult() {
return result;
}
}
我试图将所有组件绑定到HtmlInputText
数组,但是我无法解决.
我遇到了这个异常:ClassCastException
I tried to bind all components to an array of HtmlInputText
, but I could not solve it.
i got this exception : ClassCastException
推荐答案
有2个问题:
-
<c:forEach end>
包含在内.您需要从中扣除1,否则在提交时会以ArrayIndexOutOfBoundsException
结尾.
The
<c:forEach end>
is inclusive. You need to take 1 off from it, otherwise you end up withArrayIndexOutOfBoundsException
when submitting.
<c:forEach var="i" begin="0" end="#{myBean.inputsNumber - 1}">
但是,更好的方法是迭代数组本身并通过varStatus
获取索引.
A better approach is however to just iterate over the array itself and get the index by varStatus
.
<c:forEach items="#{myBean.table}" varStatus="loop">
<h:inputText value="#{myBean.table[loop.index]}" />
</c:forEach>
EL中的双精度字符被视为Double
,而不是double
.因此,您需要Double[]
而不是double[]
,否则在提交时最终会得到ClassCastException
.
A double in EL is treated as Double
, not as double
. So you need Double[]
instead of double[]
, otherwise you end up with ClassCastException
when submitting.
private Double[] table;
这篇关于动态h:inputtext以支持jsf中的Bean数组[ClassCastException]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!