作为完全 clojure 的菜鸟,我正在尝试启动一个小型教程应用程序,以熟悉 compojure。这是一个小应用程序,它允许用户添加两个数字,然后单击按钮在另一页上显示它们的总和。我按照 Mark McGranaghan 博客的指示进行操作。一切似乎都很好,直到我尝试得到我输入的两个数字的总和,而不是得到结果,我被重定向到同一页面(所以基本上我被困在本教程的第一步)。检查代码后,似乎在进行输入解析时触发了 NumberFormatException(出于某种原因)。在我所有的测试中,我都尝试过输入各种数字格式,但没有成功。这是最简单的代码版本,作者说应该可以工作(我已经尝试过最新版本github站点-相同的场景: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}))
谢谢。