2014-12-08 58 views
3

我正在使用Clojure + Ring構建運行在Glassfish 3上的Web應用程序。 如何才能訪問init函數中的ServletContext變量?如何獲取ServletContext中的ring init函數

+2

到目前爲止,您有什麼嘗試?請閱讀[我如何問一個好問題?](http://stackoverflow.com/help/how-to-ask)。 – DavidPostill 2014-12-08 08:14:30

回答

1

ServletContext(如果有)在請求映射中可用。我發現查看:context, :servlet-context:servlet-context-path的值很有用。下面是我用來確定路徑的一個小型環形中間件:

(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 2014-12-08 10:14:55

+0

我看到你正在確定路徑,但實際上並沒有調用url-in-context。不應該從wrap-context調用url-in-context(即,如果您確實希望您的應用能夠透明地工作而不管它在哪裏)? – user3810626 2016-08-11 00:08:55

+0

否,應用程序中會使用'url-in-context',例如,在視圖模型中構建鏈接。 – schaueho 2016-08-11 16:22:23

相關問題