使用带有Compojure的javax.servlet.Filter

时间:2010-05-10 21:21:51

标签: servlets openid clojure servlet-filters compojure

我正在尝试使用Clojure / Compojure构建一个简单的网站,并希望将servlet过滤器应用于请求/响应(即标准的javax.servlet.Filter实例)。

e.g。如果当前源代码是:

(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的一些任意实例。

任何想法如何有效和优雅地做到这一点?

1 个答案:

答案 0 :(得分:8)

好的,我现在已经开始工作了!感谢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))