作为整个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