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.




2 comments:

  1. with leiningen you can do a simplt line pom and generate an up to date pom file (which is what I do so that I can open pom.xml in IntelliJ and have everything preserved)

    ReplyDelete
  2. The pom I get from leiningen 1.6.1 (running "lein pom") doesn't include the clojure-maven-plugin to invoke clojure compiler. Running "mvn clean install" on it produces a jar with just the pom in it. The dependency section is fine.

    Besides, this pom is by definition derived from project.clj and should be regenerated. When I wrote this I wanted to have the pom as the primary project definition and to be able to tweak it if needed as I am used to. Now I am a bit further with clojure and don't mind skipping maven and working directly with leiningen.

    ReplyDelete