Dec 28, 2010

Creating a Clojure web project.

We can create a website using clojure programming language. It is very similar to java websites and it need a servelet container to host the site. If we can develop a .war file ti is very easy to distribute and use. So Lets try to do that. There is a simple open source war project, we can use as the base of our project. You can download it from this link;

git clone https://github.com/alienscience/leiningen-war.git

Do; lein install

git clone https://github.com/alienscience/compojure-war-example.git
(To get this you need to install GIT version control system.)


The source code will be like this.

├── project.clj
├── README.md
└── src
    ├── boot.clj
    ├── context.clj
    ├── deploy
    │   └── servlet.clj
    ├── html
    │   ├── index.html
    │   └── stylesheet.css
    ├── pages.clj
    ├── routes.clj
    └── web.xml


You can add dependencies in project.clj. Then you can check the "routes.clj" code. In that you can see some code segment like this;

"  (GET  "/app/dump" request
    (pages/dump-request request) "

When you run this in a web server and if you send a request to <host>/app/dump, it will links page which created by the class called pages.clj's "dump-reguest" function. If you view the "pages.clj" file you can see some thing like this.
(defn dump-request ...


You can add another function similar to this like;

(defn about
  (html
   [:html
    [:head
     [:title "About Me"]
     [:link {:rel "stylesheet"
             :href (context/link "/stylesheet.css")
             :type "text/css"}]]
    [:body
     [:h1 "About Me"]
     [:p "Hi ..."]]]))

And add this in the routes.clj file.
   (GET "/app/about" request
(pages/about request))

Then you can add your "about" page to the index page in html/index.html.

After that you need to compile the source code and make the war file. To do these things, first you must run;
lein compile  (you need leiningen environment)
This will download all jar files and first time it will take some time. Then, if there is no compilation error you can run

lein uberwar

Now you can see the war file. Now you need to put that war in a servlet container and run. Then visit <host>/app/about.

1 comment:

  1. Wrong git-repo above. Should be https://github.com/alienscience/compojure-war-example

    ReplyDelete

Your comments are always welcome ...