Over a million developers have joined DZone.

Adding Request Interceptor in Spring

DZone's Guide to

Adding Request Interceptor in Spring

· Integration Zone ·
Free Resource

Are your API program basics covered? Read the 5 Pillars of Full Lifecycle API Management eBook

In web applications/projects, we came across different scenarios where we need to check the request first before serving it or passing it to our main system or code.

For example in a MVC project we need to check every request that if it contains particular key/switch. That key/switch can inform us prior to processing that request to move it to particular system or portion e.g client side or admin side.

We came across the same case in which we need to verify the request first before passing it or mapping it to any controller class. For that purpose spring provides us with different listeners and hookups which can be used to overcome the cases like this.

For that we need to define a MVC request dispatcher in servlet-context.xml.


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
            <mvc:mapping path="/application/list.htm/**/">   
            <bean class="com.javapitshop.interceptor.AuthenticationInterceptor">

we can define multiple interceptors depending upon our use. In above code AuthenticationInterceptor is the class which will be called upon first on every request. If this class returns true then that particular request will be processes otherwise that request will be dropped and next request is considered for processing.

Authentication Interceptor

public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
    private HttpSession session;
     * Instantiates a new authentication interceptor.
    private AuthenticationInterceptor() {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        //Provide your implementation here.
    public boolean postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
        //Provide your implementation here.

In above code of AuthenticationInterceptor we can provide implementation of both methods preHandle() and postHandle(). Method preHandle() is being executed before processing of request and postHandle() after processing of request. You can use it depending upon your use case.

Establish API creation, publishing and discovery as a master practice with the API Management Playbook.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}