2013-07-05 53 views
1

我開發了一個用於學習目的的Scala和JSF應用程序。在這個應用程序中,我必須將所有我的Scala集合對象轉換爲Java cllectios,然後才能在JSF中呈現它。有沒有什麼簡單的方法可以用ScalaElResolver來實現,如果是的話,任何人都有ScalaElResolver的示例代碼。 在前提前致謝 PhilipJSF中的Scala集合

+0

我不知道JSF,但不是[standart conversion methods](http://stackoverflow.com/questions/495741/iterating-over-java-collections-in-scala)不適用? –

回答

3

此代碼基於Werner Punz的ScalaElResolver。 我已經剝離下來,所以它只是處理來自斯卡拉Iterablejava.lang.Iterable轉換:

class SimpleScalaElResolver extends ELResolver { 
    override def getValue(elContext: ELContext, base: AnyRef, 
         prop: AnyRef): AnyRef = { 
    println(s"SimpleElResolver: getValue: Entering: $base.$prop") 
    if (base == null) { 
     null 
    } else { 
     val method = base.getClass.getDeclaredMethod(prop.toString) 
     if (method != null) { 
     val res = method.invoke(base) 
     if (res.isInstanceOf[Iterable[_]]) { 
      val iter = res.asInstanceOf[Iterable[_]] 
      println("getValue: Wrapping as Java iterable") 
      elContext.setPropertyResolved(true) 
      JavaConversions.asJavaIterable(iter) 
     } else { 
      null 
     } 
     } else { 
     null 
     } 
    } 
    } 

這足以讓它運行使用sbt及其web插件(使用jetty引擎蓋下)即使所有其他方法仍「未執行」,如下所示:

override def getCommonPropertyType(elContext: ELContext, o: AnyRef): Class[_] = { 
    ??? 
} 

其他方法在我的情況下未被調用。

我已經從.jspx中測試過;據我所知,這也應該與JSF一起工作。


例如:如果你有一個類

class Model(val list: List[Int]) 

,並在控制器

val model = new Model(List(1)) 

httpRequest.setAttribute("model", model) 

您可以在EL

 <ul> 
      <c:forEach var="i" items="${ model.list }"> 
       <li> 
        <c:out value="${ i }"/> 
       </li> 
      </c:forEach> 
     </ul> 

所以屬性名訪問對象在EL完全匹配th的名字e val在您的模型類中。否則你會得到一個java.lang.NoSuchMethodException

+0

非常感謝您的快速響應。 –

+0

我得到一個異常警告:StandardWrapperValve [面臨的Servlet]:Servlet.service()進行的servlet面臨的Servlet拋出異常 java.lang.NoSuchMethodException:com.sun.faces.context.FacesContextImpl.externalContext() \t是java。 lang.Class.getDeclaredMethod(Class.java:1956) \t在com.philipj.scala.web.booking.ScalaElResolver.getValue(ScalaElResolver.scala:18) \t在com.sun.faces.el.DemuxCompositeELResolver._getValue( DemuxCompositeELResolver.java:176) \t at com.sun.faces.el.DemuxCompositeELResolver。 –

+0

@PhilipJ我給答案增加了一個例子。請檢查這是否解決您的問題。 – Beryllium