Saturday, January 19, 2013

Spring handler interceptor concepts....

Sometimes it is required to perform a task before displaying a webpage to the client.
Suppose you want to log the request in a table for tracking purpose or you have a common authorization mechanism to validate the user request.
Again you want to do something after the request has been processed. 
To do this kind of activites what you can use is a handler interceptor feature given by spring. 
I won't be repeating the configuration stuff here. You can find it in springs documentation itself.I will mostly concentrate on the 3 methods that should be overridden when you implement Intereceptor interface of spring.

1. preHandle :

  This is the part of block that will be executed before the request is passed to the controller. So you can put all the code you need to execute before starting the processing of request. 
Remember you can only return a boolean value from this method. 
If you return true then only the controller will be executed.

2.postHandle:

This is the part of code that will be executed when the controller has finished its job but the view is not yet rendered.
  

3.afterCompletion:

This is the part of code that gets executed after the response has been despatched :) . So you can do other tracking works / DB logging here if you want and it won't affect the response time of your request because this code will be executed only when the client has already received or the response is on its way to the client.

One most important thing to understand here is  when you return false from preHandle , postHandle and afterCompletion blocks are not executed at all. So you cannot completely rely on the thing that postHandle will be executed.
Sure thing is preHandle will be executed always no matter what happens. 

 
You can see an example of spring handler interceptor here

No comments:

Post a Comment