JSF中的Scala集合 [英] Scala Collection in JSF

查看:85
本文介绍了JSF中的Scala集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经出于学习目的开发了Scala和JSF应用程序.在这个应用程序中,我必须先将所有Scala集合对象转换为Java cllectios,然后才能在JSF中进行渲染.是否有任何简单的方法可以通过ScalaElResolver之类的方法来实现,如果是的话,那么任何人都有ScalaElResolver的示例代码. 提前致谢 菲利普

I have developed a Scala and JSF application for learning purpose. In this app I have to convert all my Scala collection objects to Java cllectios before it get rendered in JSF. Is there any easy way this can be achived with something like ScalaElResolver, if yes anybody have a sample code for ScalaElResolver. Thanks in Advance Philip

推荐答案

此代码基于 ScalaElResolver Werner Punz撰写. 我已经将其剥离,因此它只处理从Scala Iterablejava.lang.Iterable的转换:

This code is based on ScalaElResolver by Werner Punz. I have stripped it down, so it just handles the conversion from a Scala Iterable to a java.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)运行,即使所有其他方法仍然尚未实现",例如:

This is sufficient to get it running using sbt and its web plugin (which uses jetty under the hood), even if all other methods remained "not yet implemented", like this:

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

在我的情况下未调用其他方法.

The other methods were not called in my case.

我仅在.jspx内部进行过测试;据我所知,这也应该适用于JSF.

I've tested it only from within a .jspx; as far as I know this should work with JSF as well.

示例:如果您有课程

class Model(val list: List[Int])

和您的控制器中

val model = new Model(List(1))

httpRequest.setAttribute("model", model)

您可以在EL中访问实例

you can access the instance in EL

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

,因此EL中的属性名称与模型类中val的名称完全匹配.否则,您会得到java.lang.NoSuchMethodException.

so the property name in EL exactly matches the name of the val in your model class. Otherwise you get a java.lang.NoSuchMethodException.

这篇关于JSF中的Scala集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆