我正在尝试使用Clojure / Compojure构建一个简单的Web站点,并希望将servlet过滤器应用于请求/响应(即标准的
javax.servlet.Filter实例).
例如如果当前的源代码是:
(defroutes my-app (GET "/*" (html [:h1 "Hello Foo!!"])) )
我想添加一个这样的过滤器:
(defroutes my-app (GET "/*" (FILTER my-filter-name (html [:h1 "Hello Foo!!"]))) )
其中my-filter-name是javax.servlet.Filter的任意实例.
知道如何有效和优雅地做到这一点?
解决方法
好的,我现在有这个工作!感谢cgrand指向正确方向的指针!
我的解决方案涉及为过滤的servlet和过滤器链创建代理.以下代码对任何感兴趣的人
(def pass-through-filter (proxy [javax.servlet.Filter] [] (doFilter [request response #^javax.servlet.FilterChain filterchain] (do (.doFilter filterchain request response))))) (defn filter-chain [#^javax.servlet.Servlet servlet] (proxy [javax.servlet.FilterChain] [] (doFilter [request response] (.service servlet request response)))) (defn filtered-servlet [#^javax.servlet.Filter servlet-filter handler] (let [#^javax.servlet.Servlet base-servlet (servlet handler) the-filter-chain (filter-chain base-servlet)] (proxy [javax.servlet.http.HttpServlet] [] (service [request response] (.doFilter servlet-filter request response the-filter-chain)) (init [config] (.init base-servlet config))))) (defroutes my-app (GET "/*" (html [:h1 "Hello Foo!!"])) (ANY "*" [404 "Page not found"]) ) (run-server {:port 80} "/*" (filtered-servlet pass-through-filter my-app))