Module 9

Web Applications

How does the web work?

Requesting index.html

Web server = a function

A simple Clojure web application

(defn app
  [request]
  {:status 200
   :body "Hello world!"})

What is HTML?

Go to clojurebridge.org in your web browser and view the source.

Clojure web applications

Libraries we are going to use

  • Ring: handles taking in web requests and returning responses
  • Compojure: reads URLs and decides how to handle them
  • Hiccup: takes Clojure data and turns it into HTML

global-growth.web

(ns global-growth.web
  (:require [global-growth.core :as api]
            [compojure.core :refer [defroutes GET]]
            [compojure.handler :refer [site]]
            [hiccup.core :as hiccup]
            [hiccup.page :as page]
            [hiccup.form :as form]))

Getting set up for this module

Uncomment everything under the MODULE 5 line in core.clj and everything in web.clj.

Routing requests

(defroutes main-routes
  (GET "/" [] (main-page))
  (GET "/indicators" [indicator1 indicator2 year]
       (view-indicators indicator1 indicator2 year)))

Generating HTML

(hiccup/html [:header
              [:h1 "Hello world!"]
              [:h2 "I am an awesome subheader"]])
;;=> "<header><h1>Hello world!</h1>
;;    <h2>I am an awesome subheader</h2></header>"

HTML forms

Take a look at main-page.

(form/form-to {:role "form"} [:get "/indicators"]
              [:div.row
               [:div.form-group.col-md-5
                (form/label "indicator1" "Indicator 1:  ")
                (form/drop-down {:class "form-control"}
                                "indicator1"
                                (api/get-indicators))]]
              ;; ...
              (form/submit-button "Submit"))

Running a web application

Open project.clj.

Make sure the following is in the project:

:ring {:handler global-growth.web/handler}

Starting the web server

$ lein ring server

2014-04-02 21:30:06.303:INFO:oejs.Server:jetty-7.6.8.v20121106
2014-04-02 21:30:06.378:INFO:oejs.AbstractConnector:Started SelectChannelConnector@0.0.0.0:3000
Started server on port 3000

Go to http://localhost:3000/.