The situation:
I have a JavaServer Faces page and a session-scoped managed bean that has two ArrayList<Integer>
properties: one for holding a list of possible values and another for holding a list of selected values. On the JSF page there is a <h:selectManyListBox>
component with these two properties bound.
The problem: after submitting the form the selected values will be converted to string (the property of type ArrayList actually holds a couple of strings!); however, when I use a converter, I get an error message like this:
Validation Error: Value is not valid
The question: How can I bind an ArrayList<Integer>
property to the <h:selectManyListBox>
component properly?
Thank you for your kind helping me.
The concrete codes
The JSF page:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:body>
<h:form>
<h:selectManyListbox value="#{testBean.selection}">
<f:selectItems value="#{testBean.list}"></f:selectItems>
</h:selectManyListbox>
<h:commandButton action="#{testBean.go}" value="go" />
<ui:repeat value="#{testBean.selection}" var="i">
#{i}: #{i.getClass()}
</ui:repeat>
</h:form>
</h:body>
</html>
And the managed bean:
import java.io.Serializable;
import java.util.ArrayList;
@javax.faces.bean.ManagedBean
@javax.enterprise.context.SessionScoped
public class TestBean implements Serializable
{
private ArrayList<Integer> selection;
private ArrayList<Integer> list;
public ArrayList<Integer> getList()
{
if(list == null || list.isEmpty())
{
list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
}
return list;
}
public void setList(ArrayList<Integer> list)
{
this.list = list;
}
public ArrayList<Integer> getSelection()
{
return selection;
}
public void setSelection(ArrayList<Integer> selection)
{
this.selection = selection;
}
public String go()
{
// This throws an exception: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer
/*for (Integer i : selection)
{
System.out.println(i);
}*/
return null;
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…