[英]Dynamic h:inputtext to backing Bean Array in jsf [ClassCastException]
I'm using JSF 2.0 I have a problem to set Values of inputTexts to a table of double. 我正在使用JSF 2.0我有一个问题是将inputTexts的值设置为double表。
I can do this : 我可以做这个 :
<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}
Here is my backing bean : 这是我的支持bean:
@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;
}
}
I tried to bind all components to an array of HtmlInputText
, but I could not solve it. 我试图将所有组件绑定到
HtmlInputText
数组,但我无法解决它。 i got this exception : ClassCastException 我遇到了这个异常:ClassCastException
There are 2 problems: 有两个问题:
The <c:forEach end>
is inclusive. <c:forEach end>
包含在内。 You need to take 1 off from it, otherwise you end up with ArrayIndexOutOfBoundsException
when submitting. 您需要从中取1,否则在提交时最终会出现
ArrayIndexOutOfBoundsException
。
<c:forEach var="i" begin="0" end="#{myBean.inputsNumber - 1}">
A better approach is however to just iterate over the array itself and get the index by varStatus
. 然而,更好的方法是迭代数组本身并通过
varStatus
获取索引。
<c:forEach items="#{myBean.table}" varStatus="loop"> <h:inputText value="#{myBean.table[loop.index]}" /> </c:forEach>
A double in EL is treated as Double
, not as double
. EL中的double被视为
Double
,而不是double
。 So you need Double[]
instead of double[]
, otherwise you end up with ClassCastException
when submitting. 因此,您需要
Double[]
而不是double[]
,否则在提交时最终会出现ClassCastException
。
private Double[] table;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.