Tuesday, September 13, 2011

Web Fragment using Scala

Do you want to use Scala in a Java web environment, or write web fragment using scala. Or maybe you would ask: why do it at all? The answer is, because you can!

Well my little spike succeeded without any severe headache, actually so well that I did not got any at all and there was never any risk to get one.

I used SBT to build my Scala code, probably I could use it to make the full application, but I used Netbeans to create a web projet for my spike.

Setting up for SBT.

create folder for the project, for example:
>mkdir webfrag
enter the directory and create and edit build.sbt for servlet programming
>touch build.sbt

Put the following in the build-sbt file

Create a Servlet in Scala in this way.
create src/ folder and create and edit a file for the servlet, for example src/WebFragHello.scala

You can write what you want, but to make a form of HelloWorld-like example fill it with for example:

This code also "catches" the case that user parameter is not sent.A special feature seams to be that the scala code does not understand urlPattern as used in Java in the annotation, that is why I use {Array("/hello")} instead of {"/hello"}

Compile and package the code with SBT
>sbt compile
>sbt package

To make it work as a web-fragment: Put the compiled jar in WEB-INF/lib folder in a Servlet 3.0 server, you also need to put scala-library.jar in the server to be able to use scala objects. In netbeans you just need to add that jar-file to "libraries" folder in the test web project

Surf to .../context-root/hello or /context-root/hello?user=Ironic

Neet isn't it?

No comments:

Post a Comment