Servlets with Clojure

by Wolfram Saringer  (2011-08-04)
last change: 2011-08-04

A simplistic servlet implemented in Clojure

(ns at.underscore..webinterface
  (:import [javax.servlet.http HttpServlet HttpServletRequest HttpServletResponse]
  ;; see
    :name at.underscore.servlets.TestServlet
    :extends javax.servlet.http.HttpServlet
    :state localState
    :init initialize ;; avoid name clash with HttpServlet.init
  (:use clojure.contrib.pprint)

(defn -doPost [this ^HttpServletRequest req ^HttpServletResponse res]
  (.setContentType res "text/html; charset=UTF-8")
  (let [out (.getWriter res)
        text (.getParameter req "text")
        result (process-this-input text)]
    (.print out "<html><head></head><body><pre>")
    ;; pretty print for clojure data structures:
    (pprint result out)
    (.print out "</pre></body></html>")

(defn -doGet [this ^HttpServletRequest req ^HttpServletResponse res]
  (.setContentType res "text/html; charset=UTF-8")
  (.print (.getWriter res) "<html><head></head><body><form method='POST'>Text:<br><textarea cols='50' rows='20' name='text'></textarea><br><input type='submit' value='Senden' /></form></body></html>")

(defn -init [arg1 arg2]
  (println "servlet -init reached")

(defn -initialize []
  [[] (atom [])])

all articles represent the sole opinion of their respective author. all content comes without any warranty for correctnes, despite due diligence.