Interceptors – part 1

Interceptor in Spring Framework:

Spring Interceptors has the ability to pre-handle and post-handle the web requests. Each interceptor class should extend the HandlerInterceptorAdapter class. Here we will create an Interceptor by extending the HandlerInterceptorAdapter class.

You can override any of the three callback methods preHandle(), postHandle() and afterCompletion(). As the names indicate the

  • preHandle() method will be called before handling the request,
  • postHandle() method will be called after handling the request 
  • afterCompletion() method will be called after rendering the view.

Steps to Spring MVC to create Interceptor:

  1. Include a Java class which extends HandlerInterceptorAdapter class and overrides one of its methods with the name preHandle.
  2. Write the code in the preHandle method which you want Spring MVC to execute before handling the request.
  3. Put an entry of this newly added Java class in the Spring’s configuration file.

Now suppose we have a requirement that bussiness is carried only on week days and not on weekends

So before processing the User request first my Interceptor should check if the request that the application has arrived on a weekday or a week end.

If the request has been received on a week day then process the request ,if not then redirects the request to a page that mentions that business in carried on only weekdays and the request can be processed only on week days

So lets start making the changes to handle this.

Next that is pending is to make an entry in the configuration file

<bean class=”com.technicalstack.studentRegistrationController.BusinessDayBasedAccessInterceptor” />

Now the user will submit the request,it would be intercepted by the interceptor and if the day of the request is  weekend (Sunday)  the user will get message that we had set in our interceptor class



Comments are closed