Skip to main content

🧠 What REALLY Happens When You Hit a Spring Boot REST API?

🧠 What REALLY Happens When You Hit a Spring Boot REST API?

πŸ’₯ Inside the Hidden World of Filters, Interceptors & DispatcherServlet


🎬 Intro: “It’s Just a Simple API Call…” — Said Every Developer Before Debugging It

You hit this:

GET http://localhost:8080/api/user/42

🎯 And your controller returns the user info. Done, right?

😏 LOL no.

Welcome to Spring Boot, where your request goes on a rollercoaster ride through filters, interceptors, servlet containers, exception resolvers, and more — before it even thinks about reaching your controller.

Let’s deep-dive into the secret life of a REST API call in Spring Boot — with πŸ” internal mechanics, 😱 common mistakes


⚙️ 1. πŸšͺ The Request Arrives at... The Bouncer (Tomcat)

Spring Boot has an embedded server (usually Tomcat). When your app starts, it's like opening a door at a nightclub. The request knocks. πŸ•Ί

Tomcat says:
"Who dis? 🀨"
And then it lets the HTTP request enter.

🧠 Technically: Tomcat parses the socket connection and sends the request into the Servlet layer.


🧰 2. πŸš“ Filters Step In – “We Check Everyone!”

@Component
public class MyFilter implements Filter {
    public void doFilter(...) {
        // CORS? Auth header? Logging? All here
        chain.doFilter(request, response);
    }
}

πŸ” What They Do:

  • Logging πŸͺ΅
  • Header checks 🧾
  • CORS setup 🌐
  • JWT parsing πŸ”

⚠️ Can’t access Spring beans easily (they live in the servlet world 🌍).

Joke:
“Filters are like your mom at the door. If your hair’s messy or token is missing, she won’t let you go to the party.” πŸ˜†

🧠 3. 🎩 Enter the DispatcherServlet — The Real Boss

Spring's legendary DispatcherServlet is the Front Controller.

It’s the guy in the suit standing behind the scenes, pointing where every request should go.

@Bean
public DispatcherServlet dispatcherServlet() {
    return new DispatcherServlet();
}

🧭 Responsibilities:

  • Picks the right controller πŸ€–
  • Handles exceptions πŸ’₯
  • Sends responses πŸ’Œ
  • Makes sure your REST endpoint actually gets called

🚦 4. πŸ•΅️ Interceptors Arrive – “We See What You Do”

Unlike filters, interceptors live in Springland, where you get DI, beans, and control. 😎

@Component
public class MyInterceptor implements HandlerInterceptor {
    public boolean preHandle(...) { }
    public void postHandle(...) { }
    public void afterCompletion(...) { }
}

preHandle() — Before Controller

  • Block request? Return false. 🚫
  • Start timing? ⏱️
  • Check session? πŸ”‘

πŸ”„ postHandle() — After Controller

  • Modify ModelAndView 🎭
  • Log what controller returned ✅
  • Inject extra data before view is rendered 🌈

🚫 You can't modify the JSON response here if it’s a REST controller.

πŸ”š afterCompletion() — After Response Sent

  • Log request duration ⏱️
  • Cleanup (ThreadLocal, MDC) 🧹
  • Log exceptions πŸ€•

You cannot modify the response here; it’s already committed!


🎯 5. 🎯 Handler Mapping – “Where’s This Request Supposed to Go?”

Spring finds the matching controller based on:

  • URL path πŸ›£️
  • HTTP method πŸ”„
  • Annotations like @GetMapping, @PostMapping
@GetMapping("/api/user/{id}")
public User getUser(@PathVariable Long id) {
    return userService.findUser(id);
}

πŸ€– 6. Your Controller Finally Runs πŸŽ‰

Spring injects everything you love:

  • @PathVariable, @RequestParam, @RequestBody
  • Autowired beans
  • RequestContext, Headers, etc.

πŸ’£ 7. Boom! Exceptions? Enter @ControllerAdvice πŸ’¬

@ControllerAdvice
public class MyErrorHandler {
    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<?> handleIt() {
        return ResponseEntity.status(404).body("No user, bro!");
    }
}

✅ Spring checks for matching exception handlers.
❌ If none are found → you get a white-label error page (uglyyyy).


πŸ“€ 8. Response Goes Back (Backwards Flow)

The response now goes through:

  1. ResponseBodyAdvice πŸ› ️
  2. Interceptors: postHandle()afterCompletion() πŸ”„
  3. Servlet Filters (again) 🚦
  4. Embedded server (Tomcat) ✉️
  5. The client gets the final response πŸŽ‰

πŸ—Ί️ The Full Lifecycle Map


Client
 ↓
🌐 Embedded Server (Tomcat)
 ↓
πŸš“ Filters (Servlet API)
 ↓
🎩 DispatcherServlet
 ↓
πŸ•΅️ Interceptor.preHandle()
 ↓
🧭 Handler Mapping
 ↓
🎯 Controller Logic
 ↓
🧹 Interceptor.postHandle()
 ↓
πŸ“¦ ResponseBodyAdvice
 ↓
🧼 Interceptor.afterCompletion()
 ↓
πŸ›‚ Filters (post)
 ↓
✉️ Response to Client

🎯 Should I Set Headers in a Filter or an Interceptor? πŸ€”

Great question! You might be wondering:

“If I can add headers in a filter, why should I ever use an interceptor?” 🀨

πŸ› ️ Short Answer:

✅ Both can add headers.
🚫 But filters don’t know which controller is being called.
πŸ’‘ Interceptors do, and they have full Spring context.


πŸ”¬ Case Studies to Compare

1️⃣ Global Headers — Use a Filter ✅

// Filter example
response.setHeader("X-App-Version", "1.0.9");
response.setHeader("X-Frame-Options", "DENY");

Perfect for:

  • CORS headers 🌐
  • Security headers πŸ”
  • Trace IDs 🧡

2️⃣ Controller-Specific Headers — Use an Interceptor πŸ’‘

// Interceptor example
public void postHandle(...) {
  if (handler instanceof HandlerMethod hm &&
      hm.hasMethodAnnotation(MySpecialHeader.class)) {
      response.setHeader("X-Special", "true");
  }
}

Interceptors know:

  • Which controller method is running 🧠
  • What annotations are present πŸ”
  • Can access Spring beans! 🌱

3️⃣ Modify Headers After Controller — Use Interceptor or ResponseBodyAdvice πŸ”

If your controller is REST and you need to add headers *after* business logic:

  • ✅ Interceptor’s postHandle() (for headers)
  • ResponseBodyAdvice (for body + headersπŸ’¬ Interviewer May Ask:
“Can you set headers in a filter?” ✅ Yes, but only generic ones.
“Can you modify headers based on the controller?” ❌ Not in filters. ✅ Use interceptors!

🎯 Rule of Thumb:

  • Use filters when you need to do something BEFORE Spring kicks in
  • Use interceptors when you want access to Spring context, beans, and controller logic

🎁 Bonus Tip:

For REST APIs, add metadata headers like:

response.setHeader("X-Request-ID", requestId);
response.setHeader("X-User-ID", userId);

This helps in:

  • 🌐 Distributed tracing
  • πŸ” Debugging logs across microservices
  • πŸ“ˆ Monitoring APIs under load

πŸ’¬ What About You?

Ever confused filters and interceptors in a live project or interview? πŸ˜… Did someone add response headers in afterCompletion() and wonder why they didn't show up?

Share your war stories in the comments below πŸ‘‡

πŸ§ͺ Interview Questions You’ll Crush After Reading This

❓ Question ✅ Answer
Filter vs Interceptor? Filter = Servlet level
Interceptor = Spring MVC level
Can I block request in preHandle()? Yes, return false to stop the flow
Can I modify response in afterCompletion()? ❌ No. Response already committed
Where to log time taken? afterCompletion() is ideal ⏱️
Filter throws exception. Who handles it? Global exception handler won’t catch unless inside Spring context

πŸͺ„ Wrapping Up: You Just Became a Request Flow Wizard πŸ§™

Most devs debug controller issues without knowing filters or interceptors even touched the request.
But not you. πŸ’ͺ You now know exactly who does what, when, and why.

Whether it’s logging, security, tracing, or performance — this internal flow gives you superpowers in both interviews and real projects.

πŸ’¬ Your Turn:

Ever spent hours debugging a request that mysteriously vanished? Was it a filter, a missing header, or a short-circuiting preHandle()? πŸ˜… Drop your war stories in the comments πŸ‘‡


Comments

Popular posts from this blog

🐱 Tomcat vs ⚡ Netty – Which One Should You Use?

🐱 Tomcat vs ⚡ Netty – Which One Should You Use? So recently I got curious about this too πŸ€”. Everywhere in Spring Boot tutorials we see Tomcat . Then suddenly while exploring Spring WebFlux , the name Netty pops up. And I was like – “Wait, who’s this Netty guy trying to replace Tomcat?” πŸ˜… Let’s break it down with real-time examples , icons , and fun comparisons . 🐱 Tomcat – The Traditional Web Server Type: Servlet Container (blocking I/O) World: Used with Spring MVC Style: Thread-per-request model πŸ‘©‍πŸ’» Pros: Stable, widely used, battle-tested Cons: Struggles with huge concurrent connections πŸ‘‰ Example in real life: Tomcat is like a restaurant with fixed waiters 🍴. - Each customer = one thread/waiter - If too many customers come in at once → waiters run out → customers wait outside πŸšͺ ⚡ Netty – The Reactive Rockstar Type: Asynchronous Event-Driven Network Framework World: Default for Spring WebFlux Style: Event-lo...

🎭 Spring’s Secret: Why @Transactional & Friends Betray You Silently

πŸ’‘ Lesson Learned — Not a Prod Bug, But a Real Pain No, this wasn’t a production outage. Nobody screamed at me. But I sat for 3 hours wondering: “Why the heck is my @Transactional not rolling back!?” 😡‍πŸ’« “Why is Redis cache not working?” 🀯 Turned out, the issue was one silent villain: 🧱 Self-invocation 🀷 What Is @Transactional ? If you're new: @Transactional = Tells Spring to start a DB transaction when a method is called. It’ll commit if everything’s okay. It’ll rollback if something fails. 🧠 Think of it like wrapping your code in: try { beginTransaction(); // your logic commit(); } catch(Exception e) { rollback(); } πŸ•΅️ Real-Life Analogy — The Gateway Community 🏘️ Let me tell you about my society — it has a strict watchman at the gate. Here’s how it works: πŸ›‚ Watchman = Spring Proxy 🏠 Your apartment = Your service class πŸšͺ Your room = A method inside that class πŸƒ Scenario 1: Outsider Visits Your friend from outside...

🌟 My Journey – From Zero to Senior Java Tech Lead 🌟

 There’s one thing I truly believe… If I can become a Java developer, then anyone in the world can. πŸ’― Sounds crazy? Let me take you back. πŸ•“ Back in 2015… I had zero coding knowledge . Not just that — I had no interest in coding either. But life has its own plans. In 2016, I got a chance to move to Bangalore and joined a Java course at a training center. That’s where it all started — Every day, every session made me feel like: "Ohhh! Even I can be a developer!" That course didn’t just teach Java — it gave me confidence . πŸ§ͺ Two Life-Changing Incidents 1️⃣ The Interview That Wasn't Planned Halfway through my course, I had to urgently travel to Chennai to donate blood to a family member. After that emotional rollercoaster, I found myself reflecting on my skills and the future. The next day, as I was preparing for my move to Bangalore to complete the remaining four months of my course, I randomly thought — "Let me test my skills... let me just see...