我花了相当长的时间试图找到以下JSF问题的解决方案:不可能在java.util-Set上迭代。
-UI:重复(Facelets)不起作用
-A4j:重复(富面孔)不起作用
-c:forEach工作.只有在不依赖父组件定义的变量的情况下(例如,rich:dataTable)
所有这些都是相当合乎逻辑的现象,因为UIData依赖于有序的数据,而且通常一个集合是不有序的。
在我的例子中,我必须使用Hibernate(JPA)对象(PersistentSet)中定义的集合。
一个重要的注意事项:您应该使用一个集合,以防视图顺序与您无关。
解决办法.很简单。在下一个版本中,我建议它是facelets/richFaces的一部分,当然,除非有一些有效的具体理由不这样做。
1.定义自己的UI组件,扩展现有的中继器组件。我使用了一个4j:重复(HtmlAjaxRepeat)
2.覆盖metohd getDataModel
3.在Faces-config中定义组件
4.创建自定义fac卷标记定义
5.在web.xml中定义指向faclet标记定义的上下文变量。
注意:为了用于JSP而不是Facelets,您应该定义一个.tld和一个标记处理程序,这不是本文的Ojbect。
现在让我们详细地看看这些步骤:
1,2.以下是一些代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package com.myproject.components; import java.util.ArrayList; import java.util.Set; import javax.faces.model.DataModel; import javax.faces.model.ListDataModel; import org.ajax4jsf.component.html.HtmlAjaxRepeat; import org.ajax4jsf.model.SequenceDataModel; public class UIIterator extends HtmlAjaxRepeat { @SuppressWarnings ( "unchecked" ) @Override protected DataModel getDataModel() { Object current = getValue(); if (current instanceof Set){ return new SequenceDataModel( new ListDataModel( new ArrayList((Set) current))); } return super .getDataModel(); } } |
因此,由于我们不关心元素的顺序,我们只是在集合之外创建了一个新的ArrayList。现在,我们可以轻松地返回批准的海盗行为数据模型。
3.将此添加到您的Faces-config中。(我从a4j定义中复制了它)
https://movie.douban.com/people/246110479/
1 2 3 4 5 6 7 8 9 10 11 | < component > < description /> < display-name >Iterator</ display-name > < component-type >com.myproject.Iterator</ component-type > < component-class >com.myproject.components.UIIterator</ component-class > < component-extension > < component-family >javax.faces.Data</ component-family > < renderer-type >org.ajax4jsf.components.RepeatRenderera</ renderer-type > </ component-extension > </ component > |
4.这是facelets的标记定义。
https://www.douban.com/note/812043730/
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <? xml version = "1.0" encoding = "UTF-8" ?> <! DOCTYPE facelet-taglib PUBLIC "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN" "http://java.sun.com/dtd/facelet-taglib_1_0.dtd"> < facelet-taglib xmlns = "Oracle Java Technologies | Oracle" > < namespace >http://myproject.com/cust</ namespace > < tag > < tag-name >repeat</ tag-name > < component > < component-type >com.myproject.Iterator</ component-type > < renderer-type >org.ajax4jsf.components.RepeatRenderer</ renderer-type > </ component > </ tag > </ facelet-taglib > |
将此文件保存为/web-INF/facelets/custom.taglib.xml。
5.将web.xml添加到
https://greasyfork.org/he/scripts?set=476094
1 2 3 4 | < context-param > < param-name >facelets.LIBRARIES</ param-name > < param-value >/WEB-INF/facelets/custom.taglib.xml</ param-value > </ context-param > |
6.现在可以使用
1 2 3 4 5 6 7 | ... xmlns:cust" ... < cust:repeat var = "myVar" value = "${aSet}" > ... </ cust:repeat > |
我认为它比其他解决方案要整洁得多,比如定义一个定制的EL Resolver。