作爲整個clojure noob,我正在嘗試啓動一個小型教程應用程序,以便熟悉組合。這是一個讓用戶添加兩個數字的小應用程序,點擊按鈕後會在另一個頁面上顯示他們的總和。我遵循Mark McGranaghan blog的指示。一切似乎都沒問題,直到我嘗試獲得兩個我輸入的數字的總和,而不是獲得結果,我被重定向到同一頁面(所以基本上我被困在本教程的第一步)。在檢查代碼後,看起來NumberFormatException在輸入分析發生時(由於某種原因)被觸發。在我所有的測試中,我都試圖輸入各種數字格式,但沒有成功。這是最簡單的代碼版本,其撰文稱應該工作(我已經嘗試了最新版的github site - 同樣的情景:NFE):組合中的數字格式異常
(ns adder.core
(:use compojure.core)
(:use hiccup.core)
(:use hiccup.page-helpers))
(defn view-layout [& content]
(html
(doctype :xhtml-strict)
(xhtml-tag "en"
[:head
[:meta {:http-equiv "Content-type"
:content "text/html; charset=utf-8"}]
[:title "adder"]]
[:body content])))
(defn view-input []
(view-layout
[:h2 "add two numbers"]
[:form {:method "post" :action "/"}
[:input.math {:type "text" :name "a"}] [:span.math " + "]
[:input.math {:type "text" :name "b"}] [:br]
[:input.action {:type "submit" :value "add"}]]))
(defn view-output [a b sum]
(view-layout
[:h2 "two numbers added"]
[:p.math a " + " b " = " sum]
[:a.action {:href "/"} "add more numbers"]))
(defn parse-input [a b] ;; this is the place where problem occures
[(Integer/parseInt a) (Integer/parseInt b)])
(defroutes app
(GET "/" []
(view-input))
(POST "/" [a b]
(let [[a b] (parse-input a b)
sum (+ a b)]
(view-output a b sum)))
誰能告訴我更好的辦法來收杆的輸入值,爲了爲了避免這種異常?我嘗試了幾種技術,但沒有爲我工作。我在win 7機器上使用了Leningen v1.7.1和clojure 1.3。
這裏是我的project.clj文件的內容:
(defproject adder "0.0.1"
:description "Add two numbers."
:dependencies
[[org.clojure/clojure "1.3.0"]
[org.clojure/clojure-contrib "1.1.0"]
[ring/ring-core "1.0.2"]
[ring/ring-devel "1.0.2"]
[ring/ring-jetty-adapter "1.0.2"]
[compojure "1.0.1"]
[hiccup "0.3.8"]]
:dev-dependencies
[[lein-run "1.0.0"]])
和run.clj腳本:
(use 'ring.adapter.jetty)
(require 'adder.core)
(let [port (Integer/parseInt (get (System/getenv) "PORT" "8080"))]
(run-jetty #'adder.core/app {:port port}))
感謝。
感謝您的回覆,我會盡快嘗試。 – 2012-04-02 11:10:58
像魅力一樣工作,感謝您的幫助! – 2012-04-02 18:59:44