Samstag, 14. August 2010

My first Clojure Web Application

I’m a fan of LISP, so I'm known a fan of Clojure, because Clojure brings LISP features to the Java platform. I don’t know if Clojure is good programming language for production use or for my daily work, but it makes a lot of fun to develop in Clojure, just try it. My first step was to write in clojure a simple hello world web application.

I choose leinigen as build and dependency management tool and the clojure web framework Compojure to develop a super simple hello world web application.

Here are the steps how I create my first hello world web application in clojure in 3 minutes:

1.) Download Leiningen
Download the lein bash script from:

http://github.com/technomancy/leiningen/raw/stable/bin/lein

2.) Install Leiningen
Invoke the bash script with the follow command:

lein self-install

3.) Create a New Clojure Project
Creating a new project with leinigen, therefore invoke the follow command:

lein new helloworld-webapp

4.) Add Compojure Dependency
Add the compojure dependency to the project, therefore add the follow dependecies to the project.clj file.

(defproject helloworld-webapp "1.0.0-SNAPSHOT"
:description "Demo Hello World Web application"
:dependencies [
[org.clojure/clojure "1.1.0"]
[org.clojure/clojure-contrib "1.1.0"]
[compojure "0.4.0"]
[ring/ring-jetty-adapter "0.2.3"]
]
)
view raw project.clj hosted with ❤ by GitHub

5.) Create the Hello World Application
Add the follow lines of code in "src/helloworld_webapp/core.clj"

(ns helloworld-webapp.core
(:use compojure.core ring.adapter.jetty)
(:require [compojure.route :as route])
)
(defroutes example
(POST "/" [message] (str "The message was : " message))
(GET "/" [] "<form method=\"post\">
Message: </br>
<input type=\"text\" name=\"message\" value=\"\" />
<input type=\"submit\" name=\"button\" value=\"send\">
</form>"
)
(route/not-found "Page not found")
)
(run-jetty example {:port 8080})
view raw webapp.clj hosted with ❤ by GitHub

6.) Run the Web Application
To start the hello world web application invoke the follow command:

lein test

7.) Invoke the Application
Now you can use the simple web application in your favorite browser open the URL:

http://localhost:8080/

Source Code
The source code of this simple demo can be found on GitHub:
http://github.com/tux2323/clojure-helloworld-webapp


Links