Spring Framework | How to define interceptor for a spring web project

|
| By Webner

Interceptors are components that intercept requests before passing to controller and responses before rendering the view. Interceptors can intercept request and response in our web application. With the help of interceptor we can check whether a user has the authority to execute a transaction on a particular object in the database. We can use interceptors for security, logging purposes as well. Below are the steps to define interceptor in a spring web application.

Step1:

Create a java class and implement HandlerInterceptor Interface as below:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
public class ValidateRequestInterceptor implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
//write your logic here
}
    @Override
    public void afterCompletion(HttpServletRequest arg0,
    HttpServletResponse arg1, Object arg2, Exception arg3)
    throws Exception {
    //write your logic here
}
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
    Object arg2, ModelAndView arg3) throws Exception {
    //write your logic here }
}

Methods:
1. Prehandle Method: It is the very first method which will execute when a request is received. It will return a boolean value of true/false. If true will return then it will move the control to the next handler. If there is no subsequent handler then it will start executing the controller logic. If false is returned it will stop the further execution.

2.  PostHandle: It will execute after the controller and before rendering the view page.

3. after completion: It will call after the execution of the request.

Step2:

In your Spring’s application context.XML file, write following code:

<mvc:interceptors>
<bean class="your interceptor location here eg: com.mm.intercpet.interceptror name" />
</mvc:interceptors>

It will register your interceptor for intercepting request and responses of your web
application.

Leave a Reply

Your email address will not be published. Required fields are marked *