Servlet Filter and Handler Interceptor- Spring boot Implementation

Access ServletRequest multiple times, sequence of execution

Vinesh
Vinesh
Sep 22, 2020 · 4 min read

Filters and interceptors are an important part of rest applications, I have already briefed about both of them and gave a comparison between the 2 in my previous article, please check it out.

How to implement Filters?

Filter Implementation

The Servlet Filter implementation is really simple, we implement the javax.servlet.Filter, the @Order specifies the order in which the filters have to be executed. We have specified the order as 1 so this will be the first filter to be executed. The chain.doFilter called in line 18 passes the request and response object to the next filter in chain or to the handler if that’s the last filter.

Inside the doFilter method, I have checked if I can access the user IP address, requestparams from request, payload i.e., the request body from the request object. But the problem we face is the request can be read only once and if we try to access it in filter, it’ll give an error when it is being accessed in the controller. So to prevent that I have created a wrapper that extends HttpServletRequestWrapper to return a copy of the request through it’s constructor.

Now that we can access the request object multiple times, I have created a class to return the parameters from the request object which I have used in both Servlet Filter as well as Handler Interceptor for demonstration purpose.

So in the TransactionFilter I have autowired this class and passing the wrapped Request object to each of the functions and printing the values returned from them.

How to implement Handler Interceptor?

The Interceptor is very similar to that of a filter, it just has to be added to an InterceptorRegistry.

Interceptor Implementation

The Interceptor implements HandlerInterceptor interface which has 3 main methods:

  • prehandle() — called before the actual handler is executed, but the view is not generated yet
  • postHandle() — called after the handler is executed
  • afterCompletion() — called after the complete request has finished and view was generated

I have printed the elements from the request object in the same way I did in the case of filter. Now that the interceptor is ready, we need to register with InterceptorRegistry.

Register Interceptor in InterceptorRegistry

Now that we have finished coding our filters and interceptors, let’s look the hierarchy in which these methods intercept the rest api calls. I have created a controller to add a student and get student by id, let’s make calls through postman and see how the filter and interceptor perform.

RestApi call to add a Student
Sequence of print statements in filter and interceptor

If we see the sequence of print statements, the HTTP request first goes to servlet filter, where the IP address of user, and payload is printed, since there aren’t any requestparams in the request, it didn’t print any. The request then reached the pre handle method in the handler interceptor where it prints the same data and then it reaches the actual controller where the student object is saved in the database.
So the order goes from 1.Filter ➡️ 2. Interceptor ➡️ 3.Controller for a HTTP request.
From controller, the response first goes to post handle method and then to after completion method in interceptor. Let’s also check an example for requestparams.

RestApi call to get Student by id sent in requestparams
Sequence of print statements in filter and interceptor for api call with requestparams

The sequence is same as before, the only difference here is we don’t see the payload from request body since it is a get request, and the id that was sent in requestparams is visible.

You can view the code in my GitHub-repo, I’ll drop a link below. If you find this article helpful, please drop some claps and feel free to share.
This is Vinesh signing-off. Byeee 😋

The Jabberjays

Science, fantasy, and fiction for you and me.

Vinesh

Written by

Vinesh

Coder 👨‍💻, Gamer🎮 and a dog person🐶. That says a lot about me, I guess😛.

The Jabberjays

We are oddball humans striving to ink our love for technology and fantasy of all kinds.

Vinesh

Written by

Vinesh

Coder 👨‍💻, Gamer🎮 and a dog person🐶. That says a lot about me, I guess😛.

The Jabberjays

We are oddball humans striving to ink our love for technology and fantasy of all kinds.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store