如何在 ring init 函数中获取 ServletContext

3
我正在使用Clojure+Ring构建一个运行在Glassfish 3上的Web应用程序。 如何在Ring的init函数中访问ServletContext变量?

2
你目前尝试了什么?请阅读《如何提出一个好的问题》(http://stackoverflow.com/help/how-to-ask)。 - DavidPostill
1个回答

1

如果有的话,ServletContext可以在请求映射中使用。我发现查看、和值很有用。这是我使用的一个小型ring中间件,用于确定路径:

(def ^:dynamic *app-context* nil)

(defn wrap-context [handler]
 (fn [request]
  (when-let [context (:context request)]
    (logging/debug (str "Request with context " context)))
  (when-let [pathdebug (:path-debug request)]
    (logging/debug (str "Request with path-debug " pathdebug)))
  (when-let [servlet-context (:servlet-context request)]
    (logging/debug (str "Request with servlet-context " servlet-context)))
  (when-let [servlet-context-path (:servlet-context-path request)]
    (logging/debug (str "Request with servlet-context-path " servlet-context-path)))
  (binding [*app-context* (str (:context request) "/")]
     (logging/debug (str "Using appcontext " *app-context*))
     (-> request
         handler))))

(defn url-in-context [url]
    (str *app-context* url))

1
很遗憾,init函数无法访问request参数。 - Amigo
我看到你在这里确定路径,但实际上没有调用url-in-context。难道不应该从wrap-context中调用url-in-context(即,如果您实际上希望您的应用程序能够透明地工作,无论它在哪里)? - user3810626
不,url-in-context将在应用程序中使用,例如在视图模型中构建链接。 - schaueho

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接