Compojure Sessions with Sandbar


I just finished researching how to achieve persistent sessions with Compojure. The default way of doing things didn’t really look appealing to me. This whole threadsafeness business is more of a hindrance than an asset when it comes to web development IMO.

Sandbar’s stateful sessions looked just like what I want from session handling though so I decided to try it out.

To get things to work this time I had to basically replace the contents of my lib folder I’ve used for the prior tutorials in this series with the ones from sandbar, the dependency hell saga continues. A really crappy and frustrating feature of Java development it seems.

(ns hello-world
   (:use compojure.core
      ring.adapter.jetty
      sandbar.stateful-session))
   
(defroutes main-routes
   (GET "/fname*" [fname] 
      (do 
         (session-put! :name fname)
         (str fname " was put in the session.")))
   (GET "/hi*" []
      (str "Hi " (session-get :name "unknown")))
   (ANY "*" []
      {:status 404, :body "<h1>Page not found</h1>"}))

(def app (-> main-routes
             wrap-stateful-session))

(run-jetty (var app) {:join? false :port 8080})

So if you first go to http://localhost:8080/hi you will get “Hi unknown”, then go to http://localhost:8080/fname/?fname=henrik and back to http://localhost:8080/hi and you get “Hi henrik”.

Related Posts

Tags: ,