我需要重新洗牌列表中的一些数据模型的顺序,所以我用Primefaces orderlist。 该的facelet是:
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form id="main-form">
<p:panelGrid id="grid" columns="3">
<p:outputLabel value="Name" for="label"/>
<p:inputText id="label" value="#{sampleBean.obj.name}" />
<p:message for="label"/>
</p:panelGrid>
<br/><p:commandButton value="Add" action="#{sampleBean.addToList()}" update="@form" />
<br/>
<p:orderList id="rows" value="#{sampleBean.list}" converter="sample2"
itemValue="#{row}" var="row">
<p:column>
#{row.name}
</p:column>
</p:orderList>
<br/><p:commandButton value="Export" action="#{sampleBean.export()}" update="@form" />
</h:form>
<p:messages autoUpdate="true"/>
</h:body>
</html>
支持bean是:
@javax.inject.Named
@javax.faces.view.ViewScoped
public class SampleBean implements java.io.Serializable {
private List<SampleModel> list;
private SampleModel obj;
public SampleBean() {
list = new ArrayList<>();
obj = new SampleModel();
obj.setName("");
}
public void addToList() {
list.add(obj);
obj = new SampleModel();
obj.setName("");
}
public void export() {
StringBuilder buf= new StringBuilder();
for (SampleModel m: list) {
buf.append(m.getName()).append(',');
}
FacesMessage msg = new FacesMessage(buf.toString());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
public List<SampleModel> getList() {
return list;
}
public void setList(List<SampleModel> list) {
this.list = list;
}
public SampleModel getObj() {
return obj;
}
public void setObj(SampleModel obj) {
this.obj = obj;
}
}
样品模型为:
public class SampleModel {
private String name;
private String uname;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
this.uname = name.toUpperCase();
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
}
使用简单的转换就可以了。 但因为我的实际使用具有灵活的结构,所以对象将要去org.bson.Document。 使用JSON表示不工作下列转换器:
@FacesConverter("sample2")
public class Sample2Converter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
SampleModel model = new SampleModel();
try {
Document d = Document.parse(value);
model.setName(d.getString("name"));
}
catch (RuntimeException ex) {
model.setName("exception");
Logger.getLogger("Sample2Converter").log(Level.SEVERE, null, ex);
}
return model;
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value instanceof SampleModel) {
SampleModel model = (SampleModel)value;
return new Document().append("name", model.getName()).append("uname", model.getUname()).toJson();
}
else
return "invalid";
}
}
从Chrome浏览器的调试,在阿贾克斯回发,列表提交主要形式:rows_values:[对象对象],而不是主要形式:rows_values:{“名”:“苹果”}
我使用的钻嘴鱼科2.2.12,Primefaces 6.1。