Skip to content

How to use a controller interceptor

macourtney edited this page Sep 13, 2010 · 7 revisions

Added for version: 0.6

A controller interceptor can be used to intercept an incoming request to reroute, alter the request-map, or alter the response. An interceptor is simply a function which takes both the incoming request-map and the action which would be called if the request was not intercepted. The interceptor must return a response which may reroute the request to another action, or return a response.

Here is an example interceptor which simply logs “Hello World!” for every request:

(defn hello-interceptor [request-map action]
  (logging/debug "Hello World!")
  (action request-map))

Create a new conjure app called “hello_world” and add the above interceptor to the home_controller.clj file. Don’t forget to require clojure.contrib.logging in hello-controller.

Adding an Interceptor

Now lets make the interceptor intercept all actions in home-controller. To add an interceptor to a controller use the add-interceptor macro in conjure.controller.base. Add-interceptor can take either just the interceptor or the interceptor and parameters. Lets add the interceptor without any parameters first.

Add the following code to home-controller:

(add-interceptor hello-interceptor)

The above code adds the hello-interceptor to all actions in the hello-controller. If you restart your server and point your browser at the home page, “Hello World!” will be printed to your console.

Adding an Interceptor With Excludes

If you try to go to /home/list_records, “Hello World!” will actually be displayed twice, once for the call to list-records and a second time for index which list-records redirected to.

Clone this wiki locally