DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • Exploring Hazelcast With Spring Boot
  • Serverless Patterns: Web
  • How To Build Web Service Using Spring Boot 2.x
  • Develop a Spring Boot REST API in AWS: PART 4 (CodePipeline / CI/CD)

Trending

  • Secure Your API With JWT: Kong OpenID Connect
  • Maximizing Developer Efficiency and Productivity in 2024: A Personal Toolkit
  • Exploring the Frontiers of AI: The Emergence of LLM-4 Architectures
  • Modern Python: Patterns, Features, and Strategies for Writing Efficient Code (Part 1)
  1. DZone
  2. Coding
  3. Frameworks
  4. Bypassing Spring Interceptors via Decoration

Bypassing Spring Interceptors via Decoration

This article documents a simple yet very useful way of bypassing some of the configured HandlerInterceptors depending on the request's mapping.

By 
Horatiu Dan user avatar
Horatiu Dan
·
Sep. 27, 22 · Presentation
Like (2)
Save
Tweet
Share
4.8K Views

Join the DZone community and get the full member experience.

Join For Free

Whether they are built using the genuine Spring Framework or Spring Boot, such applications are widely developed and deployed these days. By trying to address simple or complex business challenges, products strongly rely on the used framework features in their attempt to offer elegant solutions. Elegant here means correct, clean, and easy to understand and maintain.

In the case of a web application, some requests are handled in a way, while others may need extra pre or post-processing or even a change in the initial request. Generally, Servlet Filters are configured and put in force in order to accommodate such scenarios.

Spring MVC applications, on the other hand, define HandlerInterceptors which are quite similar to Servlet Filters. As per the API reference, a HandlerInterceptor “allows custom pre-processing with the option of prohibiting the execution of the handler itself and custom post-processing.” Usually, a chain of such interceptors is defined based on the HandlerMapping itself, HandlerMapping being the contract that objects defining the mapping between requests and the executors of the requests shall obey.

This article documents a simple yet very useful way of bypassing some of the configured HandlerInterceptors depending on the requests’ mapping. An out-of-the-box Spring Framework HandlerInterceptor decorator is used – MappedInterceptor.

Set-up

  • Java 17
  • Maven 3.6.3
  • Spring Boot v. 2.7.3
  • A small web application that exposes a single HTTP Get operation in two different manners:
    • As a REST call (JSON representation)
    • As a web page (HTML representation)

Developing the POC

The application developed to showcase the solution is straight-forward. In order to accomplish the two previously mentioned scenarios, two controllers are defined.

The former is a @RestController annotated one and addresses the REST call, while the latter is a @Controller annotated one and handles the HTML part.

Java
 
@RestController
@Slf4j
@RequiredArgsConstructor
class JokesRestController {
 
    private final JokesService jokesService;
 
    @GetMapping("/api/jokes")
    ResponseEntity<List<Joke>> getJokes() {
        log.info("getJokes - Retrieve all jokes representation.");
        return ResponseEntity.ok(jokesService.getJokes());
    }
}
 
@Controller
@Slf4j
@RequiredArgsConstructor
class JokesController {
 
    private final JokesService jokesService;
 
    @GetMapping("/jokes")
    String getJokes(Model model) {
        log.info("getJokes - Render all jokes.");
        model.addAttribute("jokes", jokesService.getJokes());
        return "jokes";
    }
}


Both of them delegate to the same @Service component that provides the content – a few jokes – to be represented in the two aimed manners. Out of simplicity, the JokesService has the entities declared inside, as the scope of this article is focused around the web tier. In a real application, the service obviously would further delegate to a real source of data (a database repository, etc.).

A Joke entity is simply described by an identifier and the joke text and represented by the record below:

 
public record Joke(String id, String text) {
 
    public Joke(String text) {
        this(UUID.randomUUID().toString(), text);
    }
}


The detail worth observing and essential for the purpose of this article is the slight difference between the controllers’ handler mappings – /api/jokes and /jokes, respectively. Since it was decided that both ‘sections’ of this application (REST and non-REST) run in the same JVM and are deployed together, they were separated at the URL level. Basically, all REST related URLs are prefixed by /api. Pros and cons around this decision may arise, but in order to sustain the facts presented in this article, this is quite handy.

If we run it, the outcome is as desired:

  • http://localhost:8080/jokes – responds with the jokes rendered in HTML
HTML
 
HTTP/1.1 200 
Content-Type: text/html;charset=UTF-8
Content-Language: en-US
Transfer-Encoding: chunked
Date: Fri, 16 Sep 2022 08:14:31 GMT
Keep-Alive: timeout=60
Connection: keep-alive
 
<!DOCTYPE HTML>
<html lang="en">
<head>
    <title>Jokes</title>
    <meta data-fr-http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
<div>
    <table>
        <thead>
        <tr>
            <th align="left">Jokes</th>
        </tr>
        </thead>
        <tbody>
        <tr>
            <td>If Chuck Norris coughs on you, you owe him 50 bucks.</td>
        </tr>
        <tr>
            <td>Chuck Norris can make a slinky go up the stairs.</td>
        </tr>
        <tr>
            <td>Ice has Chuck Norris running through its veins.</td>
        </tr>
        </tbody>
    </table>
</div>
</body>
</html>


  • http://localhost:8080/api/jokes – responds with the jokes represented as JSON
HTML
 
HTTP/1.1 200 
Content-Type: application/json
Transfer-Encoding: chunked
Date: Fri, 16 Sep 2022 08:13:40 GMT
Keep-Alive: timeout=60
Connection: keep-alive
 
[
  {
    "id": "99798159-673b-470a-9355-09246935a42c",
    "text": "If Chuck Norris coughs on you, you owe him 50 bucks."
  },
  {
    "id": "6c073428-02c8-4a6f-a438-b4fc445adcd3",
    "text": "Chuck Norris can make a slinky go up the stairs."
  },
  {
    "id": "c9b6fcca-d12b-482f-9197-56991e799a15",
    "text": "Ice has Chuck Norris running through its veins."
  }
]


Adding Interceptors

Let’s consider the following requirement – log all requests fulfilled by the application and the session id, where applicable.

Since these are two different concerns, two different HandlerInterceptors are wired in.

Java
 
@Component
@Slf4j
public class AppInterceptor implements HandlerInterceptor {
 
    @Override
    public boolean preHandle(HttpServletRequest request, 
            HttpServletResponse response, Object handler) {
             
        log.info("preHandle - {} {} recorded", request.getMethod(), request.getRequestURI());
        return true;
    }
}
Java
 
@Component
@Slf4j
public class SessionInterceptor implements HandlerInterceptor {
 
    @Override
    public boolean preHandle(HttpServletRequest request, 
            HttpServletResponse response, Object handler) {
             
        log.info("preHandle - {} {}, session id is {}",
                request.getMethod(), request.getRequestURI(), request.getSession().getId());
        return true;
    }
}
Java
 
@EnableWebMvc
@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
 
    private final AppInterceptor appInterceptor;
    private final SessionInterceptor sessionInterceptor;
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(appInterceptor);
        registry.addInterceptor(sessionInterceptor);
    }
}

AppInterceptor logs each request, while SessionInterceptor logs the corresponding session identifier of each request, both in advance of the actual fulfillment – method preHandle() is overwritten.

If we run it again, the output is identical as before, and in the console, the following are logged:

  • http://localhost:8080/jokes
Plain Text
 
c.h.m.interceptor.AppInterceptor         : preHandle - GET /jokes recorded
c.h.m.interceptor.SessionInterceptor     : preHandle - GET /jokes, session id is 61A873D6D9697A1D1041B17A47B02285
c.h.m.controller.JokesController         : getJokes - Render all jokes.


  • http://localhost:8080/api/jokes
Plain Text
 
c.h.m.interceptor.AppInterceptor         : preHandle - GET /api/jokes recorded
c.h.m.interceptor.SessionInterceptor     : preHandle - GET /api/jokes, session id is 61A873D6D9697A1D1041B17A47B02285
c.h.m.controller.JokesRestController     : getJokes - Retrieve all jokes representation.


For each of the requests, both HandlerInterceptors were invoked, and they logged the desired information in the order they were configured. Then, the corresponding handler method was invoked, and fulfilled the request. 

Analysis and Improvements

If we analyze a bit this simple implementation, we recollect that one of the characteristics of REST is its statelessness – the session state is kept entirely on the client. Thus, in case of the REST call of this implementation, the session identifier logged by the latter HandlerInterceptor is irrelevant.

Furthermore, it means that short-circuiting this interceptor for all REST calls would be an improvement. Here, SessionInterceptor calls HttpServletRequest#getSession(), which further delegates and calls HttpServletRequest#getSession(true). This is well-known calthatch returns the session associated with the request or creates one, if necessary. In the case of REST calls, such a call is useless, pretty expensive, and may affect the overall functioning of the service if a client performs a great deal of REST calls.

Spring Framework defines the org.springframework.web.servlet.handler.MappedInterceptor, which according to its documentation, “wraps a HandlerInterceptor and uses URL patterns to determine whether it applies to a given request.” This looks exactly what is needed here, a way to bypass the SessionInterceptor in case of REST calls, in case of URLs prefixed with '/api.'

MappedInterceptor class defines a few constructors which allow including or excluding a HandlerInterceptor from being called based on URL patterns. The configuration becomes as follows:

Java
 
@EnableWebMvc
@Configuration
@RequiredArgsConstructor
public class WebConfig implements WebMvcConfigurer {
 
    private final AppInterceptor appInterceptor;
    private final SessionInterceptor sessionInterceptor;
 
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(appInterceptor);
        registry.addInterceptor(new MappedInterceptor(null, new String[] {"/api/**"}, sessionInterceptor));
    }
}


Instead of directly registering the sessionInterceptor as above, it is decorated in a MappedInterceptor instance, which excludes all URLs prefixed by '/api.'

Now in the console, the following are logged:

  • http://localhost:8080/jokes
Plain Text
 
c.h.m.interceptor.AppInterceptor         : preHandle - GET /jokes recorded
c.h.m.interceptor.SessionInterceptor     : preHandle - GET /jokes, session id is 8BD55C96F2396494FF8F72CAC5F4EE67
c.h.m.controller.JokesController         : getJokes - Render all jokes.


Both interceptors are executed before the handler method in JokesController. 

  • http://localhost:8080/api/jokes
Plain Text
 
c.h.m.interceptor.AppInterceptor         : preHandle - GET /api/jokes recorded
c.h.m.controller.JokesRestController     : getJokes - Retrieve all jokes representation.


Only the relevant interceptor is invoked before the handler method in JokesRestController. 

Conclusion

This article documented and demonstrated via a simple use case how a HandlerInterceptor invocation may be bypassed when needed by leveraging the out-of-the-box Spring Framework’s MappedInterceptor.

In real applications, such configurations might be helpful and proactively protect product development teams from hard-to-depict problems that suddenly arose and apparently out of nowhere.

API HTML Plain text REST Spring Framework Web application Requests Session (web analytics) Spring Boot Data Types

Published at DZone with permission of Horatiu Dan. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Exploring Hazelcast With Spring Boot
  • Serverless Patterns: Web
  • How To Build Web Service Using Spring Boot 2.x
  • Develop a Spring Boot REST API in AWS: PART 4 (CodePipeline / CI/CD)

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: