Saturday, October 4, 2008

Hello world in Scala and Jetty

I just started looking into Scala, which aside from the somewhat funky syntax, seems very expressive and powerful :)

For starters, this is a very good tutorial to get your feet wet.

Because a console "hello world" is too boring and easily googleable, I decided to try out the "easy Java interoperability" they tout, by trying to run a simple web server with it.

I started by grabbing a copy of Jetty (you'll just need the jetty.jar, jetty-util.jar and the servlet.jar, which are in the lib folder)

Next, I created the following folder structure:

my-server-thingie
  src
    MyServer.scala
    run.bat
    index.html
  bin
    jetty.jar
    jetty-util.jar
    servlet.jar

Then, in the MyServer.scala file, I added following code:

import org.mortbay.jetty.Server
import org.mortbay.jetty.handler.DefaultHandler
import org.mortbay.jetty.handler.ResourceHandler
import org.mortbay.jetty.handler.ContextHandler

object MyServer {
 def main(args: Array[String]) {
  var server = new Server(8080)
  var fileHandler = new ResourceHandler()
  var defaultHandler = new DefaultHandler()
  
  fileHandler.setResourceBase(".")
  server.addHandler(fileHandler)
  server.addHandler(defaultHandler)
  
  server.start();
 }
}

My run.bat file looks like this (note: you'll need to either setup the path, or point the second line to the bin folder in your scala copy):

@set file=MyServer
@set path=%PATH%;C:\scala-2.7.1.final\bin;
@set bin=../bin/
@set cp=%BIN%;%BIN%jetty.jar;%BIN%jetty-util.jar;%BIN%servlet.jar
@call scalac -d %BIN% -optimise -cp %CP% %FILE%.scala
@call scala -cp %CP% %FILE%
@pause

Now just write "Hello world" in your index.html file and point your browser to http://localhost:8080/index.html

Done!

No comments:

Post a Comment