📜  Clojure-应用程序

📅  最后修改于: 2020-11-05 04:09:42             🧑  作者: Mango


Clojure有一些贡献的库,这些库可以创建基于桌面基于Web的应用程序。让我们讨论其中的每一个。

Sr.No. Applications & Description
1 Desktop – See-saw

See-saw is a library which can be used for creating desktop applications.

2 Desktop – Changing the Value of Text

The value of the content in the window can be changed by using the ‘config!’ option. In the following example the config! option is used to change the window content to the new value of “Good Bye”.

3 Desktop – Displaying a Modal Dialog Box

A modal dialog box can be shown by using the alert method of the see-saw class. The method takes the text value, which needs to be shown in the modal dialog box.

4 Desktop – Displaying Buttons

Buttons can be displayed with the help of the button class.

5 Desktop – Displaying Labels

Labels can be displayed with the help of the label class.

6 Desktop – Displaying Text Fields

Text Fields can be displayed with the help of the text class.

Web应用程序-简介

要在Clojure中创建Web应用程序,您需要使用Ring应用程序库,该库可在以下链接中找到:https://github.com/ring-clojure/ring

您需要确保从站点下载了必要的jar,并确保将其添加为Clojure应用程序的依赖项。

Ring框架提供以下功能-

  • 进行设置,以使HTTP请求作为常规Clojure HashMap进入您的Web应用程序,并且同样进行处理,以便您可以将响应作为HashMap返回。

  • 提供规范,准确描述那些请求和响应映射的外观。

  • 带上Web服务器(Jetty)并将您的Web应用程序连接到该服务器。

Ring框架可以自动启动Web服务器,并确保Clojure应用程序可在该服务器上运行。然后,也可以使用Compojure框架。这样一来,人们就可以创建路由,而这正是大多数现代Web应用程序的开发方式。

创建第一个Clojure应用程序-以下示例显示如何在Clojure中创建第一个Web应用程序。

(ns my-webapp.handler
   (:require [compojure.core :refer :all]
      [compojure.route :as route]
      [ring.middleware.defaults :refer [wrap-defaults site-defaults]]))
(defroutes app-routes
   (GET "/" [] "Hello World")
   (route/not-found "Not Found"))
(def app
   (wrap-defaults app-routes site-defaults))

让我们看一下程序的以下方面-

  • “ defroutes”用于创建路由,以便可以将针对Web应用程序对不同路由的请求定向到Clojure应用程序中的不同功能。

  • 在上面的示例中,“ /”被称为默认路由,因此当您浏览到Web应用程序的基础时,字符串“ Hello World”将被发送到Web浏览器。

  • 如果用户点击了Clojure应用程序无法处理的任何URL,则它将显示字符串“ Not Found”。

当您运行Clojure应用程序时,默认情况下,您的应用程序将以localhost:3000的形式加载,因此,如果浏览到此位置,您将收到以下输出。

Clojure应用

Web应用程序–向Web应用程序添加更多路由

您还可以将更多路由添加到Web应用程序。以下示例显示了如何实现此目的。

(ns my-webapp.handler
   (:require [compojure.core :refer :all]
      [compojure.route :as route]
      [ring.middleware.defaults :refer [wrap-defaults site-defaults]]))
(defroutes app-routes
   (GET "/" [] "Hello World")
   (GET "/Tutorial" [] "This is a tutorial on Clojure")
   (route/not-found "Not Found"))
(def app
   (wrap-defaults app-routes site-defaults))

您可以看到,在应用程序中添加路由就像在URL路由中添加另一个GET函数一样容易。 (获取“ / Tutorial” []“这是Clojure的教程”)

如果浏览到http:// localhost:3000 / Tutorial位置,您将收到以下输出。

本地主机