原帖地址:http://java.ociweb.com/mark/clojure/article.html#WebApps
作者:R. Mark Volkmann
译者:RoySong
Web应用
有多种Clojure库来创建Web应用。一个常见的选择是采用Compojure,可以从
http://github.com/weavejester/compojure/tree/master 获得。最新的版本可以从Git 资源库中获取到(假设
已经安装了Git):
git clone git://github.com/weavejester/compojure.gitgit clone git://github.com/weavejester/compojure.git
上述命令会在当前目录下建立一个compojure目录,然后从
http://cloud.github.com/downloads/weavejester/compojure/deps.zip 下载所需的jar包,然后将deps.zip放置在
compojure目录下并将它的内容解压到
deps子目录中去。
要构建compojure.jar,在
compojure目录中运行
ant即可。
需要升级Compojure时,在compojure目录中运行以下命令:
git pull
ant clean deps jar
deps子目录下面的所有jar包都必须包含在classpath中,打成这个目的的一种方法是修改
clj脚本,然后用它来
运行web应用。在用来运行clojure.main的
java命令后加上"-cp $CP
",并且在设置CP之前加上以下的命令:
# Set CP to a path list that contains clojure.jar
# and possibly clojure-contrib.jar.
COMPOJURE_DIR=path-to-compojure-dir
COMPOJURE_JAR=$COMPOJURE_DIR/compojure.jar
CP=$CP:$COMPOJURE_JAR
for file in $COMPOJURE_DIR/deps/*.jar
do
CP=$CP:$file
done
下面是一个简单的Compojure Web应用例子:
(ns com.ociweb.hello (:use compojure)) (def host "localhost") (def port 8080) (def in-path "/hello") (def out-path "/hello-out") (defn html-doc "generates well-formed HTML for a given title and body content" [title & body] (html (doctype :html4) [:html [:head [:title title]] [:body body]])) ; Creates HTML for input form. (def hello-in (html-doc "Hello In" (form-to [:post out-path] "Name: " (text-field {:size 10} :name "World") [:br] (reset-button "Reset") (submit-button "Greet")))) ; Creates HTML for result message. (defn hello-out [name] (html-doc "Hello Out" [:h1 "Hello, " name "!"])) (defroutes hello-service ; The following three lines map HTTP methods ; and URL patterns to response HTML. (GET in-path hello-in) (POST out-path (hello-out (params :name))) (ANY "*" (page-not-found))) ; displays ./public/404.html by default (println (str "browse http://" host ":" port in-path)) ; -> browse http://localhost:8080/hello (run-server {:port port} "/*" (servlet hello-service))