brush clojure

Friday, November 18, 2011

Sample Clojure/Compojure Web Application with Maven and IntelliJ

After learning a bit of Clojure I decided to start a simple Clojure web application project to try more things out. I expected I would easily find tons of sample projects to start from, but at the end I couldn't find a single Getting Started for the type of project I wanted:
- I am too comfortable with Maven to want to change it with leiningen or anything else.
- Starting a quick Jetty server is great but I still want to have the traditional WAR.

I don't know, may be these are all things a hard-core Clojure developers laugh at, but that is what I feel comfortable with at the moment.

Googling I found this very complete and precise blog entry:
http://blog.kartikshah.com/2010/12/how-to-intellij-idea-for.html It all worked as described, using leiningen. I tweaked it a bit:
- mavenized it: removed leningen, edited the pom to add clojure compilation using the clojure-maven-plugin;
- removed the GAE stuff;
- renamed a few folders and packages.

See below the core Clojure class implementing HttpServlet and routing request using Compojure:

(ns pwc.core
  (:gen-class :extends javax.servlet.http.HttpServlet)
  (:use compojure.core
        ring.util.servlet)
  (:require [compojure.route :as route]))

(defroutes hello
  (GET "/" [] "Hello World Wide Web!")
  (GET "/user/:id" [id]
    (str "Hello user " id ))
  (route/not-found "Page not found"))

(defservice hello)

The Compojure routing is explained here

The project is available at git. Build a war from maven or import the pom.xml in IntelliJ and run the war artifact in a servlet container. I ran it in tomcat, starting conservative: in the run configuration I deployed the non-exploded war, running the package goal before launch.

**NOTE** One month later, I don't think this is the way to go if you want to dive into Clojure. I've joinde the leiningen/emacs way.