How to script scala directly in JSP pages?

jsp, scala

Solution

Edit: check http://scalate.fusesource.org/index.html: Scala Template Engine: like JSP without the crap but with added Scala coolness. I just stumbled upon this while checking the #scala twitter feed.

You can have a look at http://github.com/alandipert/step. It looks like an active project with just enough to let you write Scala code mixed with xhtml code. Whether you can script like PHP, I don't know. One of the difference is that with JSP/PHP, you include a program inside an HTML page where as with `step` you include some `xml` into a Scala file.

There is going to be a bit of a learning curve with Scala and `sbt` but I think it's worth it to take advantage of Scala.

The other thing you can do is to write a custom JSP tag that lets you run some Scala code through the interpreter. I did a proof of concept and this seems to work:

/**
 * Proof of concept, you can run Scala code in a JSP tag.
 * Works with jetty and sbt.
 */
class ScalaScriptTag extends BodyTagSupport {

  override def doAfterBody():Int = {
    try { 
      val settings = new Settings(str => println(str))
      // interpreter classloader does not seem to pick up classes from the parent
      settings.classpath.value = 
        "lib_managed/compile/jsp-api-2.1-6.1.14.jar;" + 
        "lib_managed/compile/servlet-api-2.5-6.1.14.jar"
      var i = new Interpreter(settings) {
        override def parentClassLoader():ClassLoader = {
          return Thread.currentThread().getContextClassLoader();
        }
      }
      i.bind("pageContext", "javax.servlet.jsp.PageContext", pageContext)
      val source = Source.fromString(getBodyContent.getString)
      for (line <- source.getLines) { i.interpret(line) }
    } catch {
      case ioe: IOException => 
        throw new JspException(ioe.getMessage())
    }
    Tag.SKIP_BODY
  }

}                       

Problem

Is there any scala JSP engine, or is there going to be any? i know about the scala web framework lift, but it seems more like tags. i am looking for a way to script like PHP. thanks.

Original source