> 1. Loading .clj files
> Is it possible to load up .clj files from the classpath of an
> arbitrary java app? For example, could you proxy HttpServlet and run
> your servlet as a .clj from within a servlet container?
Hi Todd, here's a pattern for doing what you want;
1.) Create svlt/Svlt.clj as below
2.) Compile it separately using
(binding [*compile-path* "./tmp"] (compile 'svlt.Svlt))
3.) cp ./tmp/* [tomcat]/myctx/WEB-INF/classes/
4.) cp clojure.jar to myctx/WEB-INF/lib
It is better to have clojure.jar in each context's WEB-INF
as then class loading works correctly.
5.) Create your app clj functions in say myapp/clfns.clj
(as below) and copy this (not compiled)
to myctx/WEB-INF/classes/myapp/clfns.clj
6.) Add to myctx/WEB-INF/web.xml;
<servlet>
<servlet-name>Svlt</servlet-name>
<servlet-class>svlt.Svlt</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Svlt</servlet-name>
<url-pattern>/svlt/*</url-pattern>
7.) Open http://whatever/myctx/svlt/myapp.clfns/html-hi
; -------------------- svlt/Svlt.clj
(ns svlt.Svlt
(import (javax.servlet.http HttpServletRequest
HttpServletResponse))
(:gen-class :extends javax.servlet.http.HttpServlet))
(def re-ipath #"\/(.*)\/(.*)")
(defn -service
[this #^HttpServletRequest req #^HttpServletRequest rsp]
(let [ipath (.getPathInfo req)
g (re-matches re-ipath ipath)
_ (when (nil? g) (throw (java.io.IOException.
(str "Invalid svlt ipath (parse): " ipath))))
[_ ns-sym req-fn-nm] g
ns-sym (symbol ns-sym)
found-ns (find-ns ns-sym)
found-ns (if (nil? found-ns)
(let [n (create-ns ns-sym)] (require ns-sym) n)
found-ns)
_ (when (nil? found-ns) (throw (java.io.IOException.
(str "Namespace not found for: " ns-sym))))
req-fn (get (ns-publics ns-sym) (symbol req-fn-nm)) ]
(req-fn req rsp)))
; --------------------- myapp/clfns.clj
(ns myapp.clfns
(:import (javax.servlet.http HttpServletRequest
HttpServletResponse)))
(defn html-hi
[#^HttpServletRequest req #^HttpServletResponse rsp]
(.setContentType rsp "text/html")
(with-open [wtr (java.io.PrintWriter. (.getOutputStream rsp))]
(.println wtr "<html><body><p>Hi</p></body></html>"))))
Notes;
- to update, simply copy new app clj file/s to WEB-INF/classes and
reload the context.
- Borrow http://github.com/weavejester/hiccup for some cool html
generation stuff.
- you should be able to adapt the above (namespace requiring) to your
other java integration needs.
-Rgds, Adrian.
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en