---
title: "Clojure-JVM上的函数式编程语言(16)Web应用 作者: R. Mark Volkmann"
author: "songry"
date: "2011-11-19T11:37:11Z"
tags: []
categories: ["编程语言"]
slug: "clojure-jvm-16-web-r-mark-volkmann"
draft: false
lastmod: "2011-11-19T11:36:51Z"
id: 1266565
url: "https://roysong.iteye.com/blog/1266565"
---

原帖地址：http://java.ociweb.com/mark/clojure/article.html#WebApps

作者：R. Mark Volkmann  

译者：RoySong

 

# Web应用

    有多种Clojure库来创建Web应用。一个常见的选择是采用Compojure，可以从

[http://github.com/weavejester/compojure/tree/master](http://github.com/weavejester/compojure/tree/master) 获得。最新的版本可以从[Git](http://git-scm.com/) 资源库中获取到（假设

已经安装了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](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))
```

 

![](http://java.ociweb.com/mark/clojure/images/Compojure1.png)![](http://java.ociweb.com/mark/clojure/images/Compojure2.png)