Back to Web Layer: Controllers & Request Mapping
Q5Question 5 of 6

What happens when an HTTP request reaches a Spring Boot REST API

Answer: When an HTTP request reaches a Spring Boot REST API, it flows through the embedded Tomcat server, Servlet Filters, DispatcherServlet, HandlerInterceptors, the controller method, the service layer, and back through Jackson serialization to produce the JSON response.

Key Concepts
  • The embedded Tomcat server receives the TCP connection, parses the HTTP request, and passes it to the Servlet Filter chain before it reaches DispatcherServlet.
  • Servlet Filters run first (CORS, security, encoding), then DispatcherServlet delegates to HandlerMapping, HandlerInterceptor, HandlerAdapter, and the controller method.
  • The controller method receives deserialized parameters (@PathVariable, @RequestParam, @RequestBody via Jackson) and returns a Java object.
  • HttpMessageConverter (MappingJackson2HttpMessageConverter) serializes the returned object to JSON and writes it to the HTTP response body.
  • @ControllerAdvice with @ExceptionHandler catches exceptions thrown anywhere in the controller or service layer and returns a structured error response.
  • The full lifecycle is: Tomcat -> Filter -> DispatcherServlet -> Interceptor.preHandle -> Controller -> Service -> Repository -> Interceptor.postHandle -> JSON serialization -> Interceptor.afterCompletion -> Filter -> Tomcat -> Client.

Definition

When an HTTP request reaches a Spring Boot REST API, it flows through the embedded Tomcat server, Servlet Filters, DispatcherServlet, HandlerInterceptors, the controller method, the service layer, and back through Jackson serialization to produce the JSON response.
  • Embedded Tomcat is the HTTP server that Spring Boot starts inside your JVM; it listens on a port, accepts TCP connections, and parses HTTP requests into HttpServletRequest objects.
  • Servlet Filter is a component that runs before and after DispatcherServlet, handling cross-cutting concerns like CORS headers, character encoding, and security.
  • DispatcherServlet is the front controller that routes the request to the correct controller method through HandlerMapping and HandlerAdapter.
  • HttpMessageConverter is the component that converts between Java objects and HTTP message bodies; MappingJackson2HttpMessageConverter handles JSON using the Jackson library.
  • @ControllerAdvice is a centralized exception handler that catches exceptions from any controller and returns a structured error response.

Think of a customer (HTTP request) visiting National Bank of India's main branch. First, the customer passes through a security checkpoint (Servlet Filter). Then the reception desk (DispatcherServlet) checks the request slip and directs them to the right counter. A timing stamp machine (HandlerInterceptor) records entry time. The counter clerk (Controller) takes the request, consults the back office (Service layer), which checks the vault records (Repository). The clerk writes the response on a standard bank form (Jackson serializes to JSON), the timing machine stamps exit time, the customer passes through security again, and walks out the door with the response.

Understanding the Concepts

What happens step by step when a request arrives?

Let us trace a real request: GET /api/accounts/SAV2001 sent to a Spring Boot REST API running on port 8080.

  1. TCP connection: the client opens a TCP connection to localhost:8080.
  2. HTTP parsing: Tomcat's NIO connector reads the raw bytes and parses them into an HttpServletRequest object.
  3. Filter chain: the request passes through registered Servlet Filters (CharacterEncodingFilter, CorsFilter, SecurityFilterChain).
  4. DispatcherServlet.doDispatch(): the front controller receives the request.
  5. HandlerMapping: RequestMappingHandlerMapping matches GET /api/accounts/{id} to AccountController.getAccount(String id).
  6. Interceptor.preHandle: all registered HandlerInterceptors run their preHandle method.
  7. HandlerAdapter: RequestMappingHandlerAdapter invokes the controller method, binding SAV2001 to the @PathVariable String id parameter.
  8. Controller -> Service -> Repository: the controller calls the service, which calls the repository.
  9. Return value: the controller returns a Java object (Account record) or ResponseEntity.
  10. Interceptor.postHandle: runs after the controller but before the response is written.
  11. HttpMessageConverter: MappingJackson2HttpMessageConverter serializes the Account to JSON.
  12. Interceptor.afterCompletion: runs after the response is committed. Used for cleanup and logging.
  13. Filter chain (reverse): filters run their post-processing.
  14. HTTP response: Tomcat writes the HTTP response bytes to the TCP connection. The client receives the JSON.
JAVA
package com.bank;

public class RequestLifecycleSteps {
    public static void main(String[] args) {
        System.out.println("GET /api/accounts/SAV2001 lifecycle:");
        System.out.println("  1. TCP -> Tomcat NIO Connector");
        System.out.println("  2. HTTP parsing -> HttpServletRequest");
        System.out.println("  3. CharacterEncodingFilter");
        System.out.println("  4. CorsFilter");
        System.out.println("  5. SecurityFilterChain (if Spring Security)");
        System.out.println("  6. DispatcherServlet.doDispatch()");
        System.out.println("  7. RequestMappingHandlerMapping -> AccountController.getAccount()");
        System.out.println("  8. RequestTimingInterceptor.preHandle()");
        System.out.println("  9. RequestMappingHandlerAdapter.handle()");
        System.out.println("  10. AccountController.getAccount(\"SAV2001\")");
        System.out.println("  11. AccountService.findById(\"SAV2001\")");
        System.out.println("  12. AccountRepository.findById(\"SAV2001\")");
        System.out.println("  13. Controller returns Account object");
        System.out.println("  14. RequestTimingInterceptor.postHandle()");
        System.out.println("  15. MappingJackson2HttpMessageConverter -> JSON");
        System.out.println("  16. RequestTimingInterceptor.afterCompletion()");
        System.out.println("  17. Response: 200 OK + JSON body");
    }
}
TEXT
Expected output:
GET /api/accounts/SAV2001 lifecycle:
  1. TCP -> Tomcat NIO Connector
  2. HTTP parsing -> HttpServletRequest
  3. CharacterEncodingFilter
  4. CorsFilter
  5. SecurityFilterChain (if Spring Security)
  6. DispatcherServlet.doDispatch()
  7. RequestMappingHandlerMapping -> AccountController.getAccount()
  8. RequestTimingInterceptor.preHandle()
  9. RequestMappingHandlerAdapter.handle()
  10. AccountController.getAccount("SAV2001")
  11. AccountService.findById("SAV2001")
  12. AccountRepository.findById("SAV2001")
  13. Controller returns Account object
  14. RequestTimingInterceptor.postHandle()
  15. MappingJackson2HttpMessageConverter -> JSON
  16. RequestTimingInterceptor.afterCompletion()
  17. Response: 200 OK + JSON body

How does the embedded Tomcat server receive the request?

Spring Boot starts an embedded Tomcat server during application startup. The server listens on the configured port (default 8080) using NIO (Non-blocking I/O). When a client connects, Tomcat accepts the TCP connection, reads the HTTP request bytes, and creates an HttpServletRequest and HttpServletResponse object.

You do not deploy a WAR file to an external Tomcat. The server runs inside your application.

JAVA
package com.bank;

public class EmbeddedTomcatExplained {
    public static void main(String[] args) {
        System.out.println("Embedded Tomcat in Spring Boot:");
        System.out.println("  1. SpringApplication.run() creates ApplicationContext");
        System.out.println("  2. TomcatServletWebServerFactory creates Tomcat instance");
        System.out.println("  3. DispatcherServlet registered on / pattern");
        System.out.println("  4. Tomcat starts, listens on port 8080 (NIO connector)");
        System.out.println("  5. Client connects -> Tomcat accepts TCP connection");
        System.out.println("  6. Tomcat reads HTTP bytes -> creates HttpServletRequest");
        System.out.println("  7. Passes to Servlet Filter chain -> DispatcherServlet");
        System.out.println();
        System.out.println("Alternatives to Tomcat:");
        System.out.println("  Jetty:    spring-boot-starter-jetty");
        System.out.println("  Undertow: spring-boot-starter-undertow");
    }
}
TEXT
Expected output:
Embedded Tomcat in Spring Boot:
  1. SpringApplication.run() creates ApplicationContext
  2. TomcatServletWebServerFactory creates Tomcat instance
  3. DispatcherServlet registered on / pattern
  4. Tomcat starts, listens on port 8080 (NIO connector)
  5. Client connects -> Tomcat accepts TCP connection
  6. Tomcat reads HTTP bytes -> creates HttpServletRequest
  7. Passes to Servlet Filter chain -> DispatcherServlet

Alternatives to Tomcat:
  Jetty:    spring-boot-starter-jetty
  Undertow: spring-boot-starter-undertow

How does JSON serialization happen?

When a @RestController method returns a Java object, Spring uses HttpMessageConverter to convert it to JSON. The default converter is MappingJackson2HttpMessageConverter, which uses the Jackson library.

Jackson reads the public getters (or record components) of the returned object and writes them as JSON key-value pairs. The Content-Type header is set to application/json.

JAVA
package com.bank.model;

import java.math.BigDecimal;

public record PaymentResponse(
    String transactionId,
    String accountId,
    BigDecimal amount,
    String status
) {}
JAVA
package com.bank.controller;

import com.bank.model.PaymentResponse;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;

@RestController
@RequestMapping("/api/payments")
public class PaymentController {

    @PostMapping
    public PaymentResponse processPayment() {
        // Controller returns a Java object
        return new PaymentResponse(
            "TXN-000042",
            "SAV2001",
            new BigDecimal("75000.00"),
            "SUCCESS"
        );
        // Jackson converts this to JSON automatically
    }
}
TEXT
Expected output (curl -X POST http://localhost:8080/api/payments):
{"transactionId":"TXN-000042","accountId":"SAV2001","amount":75000.00,"status":"SUCCESS"}

Jackson serialization steps:
  1. Finds record components: transactionId, accountId, amount, status
  2. Calls accessor methods: transactionId(), accountId(), amount(), status()
  3. Writes JSON: {"transactionId":"TXN-000042",...}
  4. Sets Content-Type: application/json

What is a complete banking project tracing the request lifecycle?

This project traces a payment request through every layer with logging at each step: filter, interceptor, controller, service, repository.

Project structure

DIAGRAM
bank-lifecycle-demo/
├── pom.xml
└── src/
    ├── main/
    │   └── java/
    │       └── com/
    │           └── bank/
    │               ├── BankLifecycleDemoApp.java
    │               ├── model/
    │               │   ├── Account.java
    │               │   └── TransferRequest.java
    │               ├── repository/
    │               │   └── AccountRepository.java
    │               ├── service/
    │               │   └── TransferService.java
    │               ├── controller/
    │               │   └── TransferController.java
    │               ├── filter/
    │               │   └── RequestLoggingFilter.java
    │               ├── interceptor/
    │               │   └── TimingInterceptor.java
    │               ├── advice/
    │               │   └── GlobalExceptionHandler.java
    │               └── config/
    │                   └── WebConfig.java
    └── test/
        └── java/
            └── com/
                └── bank/
                    └── controller/
                        └── TransferControllerTest.java

pom.xml

XML
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
    syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>

    syn-kw"><parentsyn-kw">>
        syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
        syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
        syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
    syn-kw"></parentsyn-kw">>

    syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
    syn-kw"><artifactIdsyn-kw">>bank-lifecycle-demosyn-kw"></artifactIdsyn-kw">>
    syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>

    syn-kw"><propertiessyn-kw">>
        syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
    syn-kw"></propertiessyn-kw">>

    syn-kw"><dependenciessyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-starter-websyn-kw"></artifactIdsyn-kw">>
        syn-kw"></dependencysyn-kw">>
        syn-kw"><dependencysyn-kw">>
            syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
            syn-kw"><artifactIdsyn-kw">>spring-boot-starter-testsyn-kw"></artifactIdsyn-kw">>
            syn-kw"><scopesyn-kw">>testsyn-kw"></scopesyn-kw">>
        syn-kw"></dependencysyn-kw">>
    syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>

Account.java

JAVA
package com.bank.model;

import java.math.BigDecimal;

public record Account(
    String accountId,
    String holderName,
    BigDecimal balance
) {
    public Account withBalance(BigDecimal newBalance) {
        return new Account(accountId, holderName, newBalance);
    }
}

TransferRequest.java

JAVA
package com.bank.model;

import java.math.BigDecimal;

public record TransferRequest(
    String fromAccountId,
    String toAccountId,
    BigDecimal amount
) {}

AccountRepository.java

JAVA
package com.bank.repository;

import com.bank.model.Account;
import jakarta.annotation.PostConstruct;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

@Repository
public class AccountRepository {

    private final Map<String, Account> store = new ConcurrentHashMap<>();

    @PostConstruct
    void init() {
        store.put("SAV2001", new Account("SAV2001", "Priya", new BigDecimal("150000.00")));
        store.put("CUR3001", new Account("CUR3001", "Rajesh", new BigDecimal("500000.00")));
        System.out.println("[Repository] Initialized with 2 accounts");
    }

    public Optional<Account> findById(String id) {
        System.out.println("[Repository] findById: " + id);
        return Optional.ofNullable(store.get(id));
    }

    public void save(Account account) {
        System.out.println("[Repository] save: " + account.accountId() + " balance=" + account.balance());
        store.put(account.accountId(), account);
    }
}

TransferService.java

JAVA
package com.bank.service;

import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

@Service
public class TransferService {

    private final AccountRepository accountRepository;

    public TransferService(AccountRepository accountRepository) {
        this.accountRepository = accountRepository;
    }

    public Map<String, Object> transfer(String fromId, String toId, BigDecimal amount) {
        System.out.println("[Service] transfer: " + fromId + " -> " + toId + " amount=" + amount);

        Account from = accountRepository.findById(fromId)
            .orElseThrow(() -> new IllegalArgumentException("Account not found: " + fromId));
        Account to = accountRepository.findById(toId)
            .orElseThrow(() -> new IllegalArgumentException("Account not found: " + toId));

        if (from.balance().compareTo(amount) < 0) {
            throw new IllegalStateException("Insufficient balance in " + fromId);
        }

        accountRepository.save(from.withBalance(from.balance().subtract(amount)));
        accountRepository.save(to.withBalance(to.balance().add(amount)));

        return Map.of(
            "status", "SUCCESS",
            "from", fromId,
            "to", toId,
            "amount", amount,
            "fromBalance", from.balance().subtract(amount),
            "toBalance", to.balance().add(amount)
        );
    }
}

RequestLoggingFilter.java

JAVA
package com.bank.filter;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Order(1)
public class RequestLoggingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        var httpReq = (HttpServletRequest) request;
        System.out.println("[Filter] ENTER: " + httpReq.getMethod() + " " + httpReq.getRequestURI());

        chain.doFilter(request, response);

        var httpResp = (HttpServletResponse) response;
        System.out.println("[Filter] EXIT: status=" + httpResp.getStatus());
    }
}

TimingInterceptor.java

JAVA
package com.bank.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class TimingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        request.setAttribute("startTime", System.currentTimeMillis());
        System.out.println("[Interceptor] preHandle: " + handler.getClass().getSimpleName());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) {
        System.out.println("[Interceptor] postHandle: controller returned");
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) {
        long start = (long) request.getAttribute("startTime");
        long ms = System.currentTimeMillis() - start;
        System.out.println("[Interceptor] afterCompletion: " + ms + "ms");
    }
}

GlobalExceptionHandler.java

JAVA
package com.bank.advice;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Map<String, String> handleNotFound(IllegalArgumentException ex) {
        System.out.println("[ExceptionHandler] " + ex.getMessage());
        return Map.of("error", ex.getMessage());
    }

    @ExceptionHandler(IllegalStateException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> handleBadRequest(IllegalStateException ex) {
        System.out.println("[ExceptionHandler] " + ex.getMessage());
        return Map.of("error", ex.getMessage());
    }
}

WebConfig.java

JAVA
package com.bank.config;

import com.bank.interceptor.TimingInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    private final TimingInterceptor timingInterceptor;

    public WebConfig(TimingInterceptor timingInterceptor) {
        this.timingInterceptor = timingInterceptor;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(timingInterceptor)
                .addPathPatterns("/api/**");
    }
}

TransferController.java

JAVA
package com.bank.controller;

import com.bank.model.TransferRequest;
import com.bank.service.TransferService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/transfers")
public class TransferController {

    private final TransferService transferService;

    public TransferController(TransferService transferService) {
        this.transferService = transferService;
    }

    @PostMapping
    public Map<String, Object> transfer(@RequestBody TransferRequest request) {
        System.out.println("[Controller] transfer: " + request);
        return transferService.transfer(
            request.fromAccountId(),
            request.toAccountId(),
            request.amount()
        );
    }
}

BankLifecycleDemoApp.java

JAVA
package com.bank;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class BankLifecycleDemoApp {
    public static void main(String[] args) {
        SpringApplication.run(BankLifecycleDemoApp.class, args);
    }
}

TransferControllerTest.java

JAVA
package com.bank.controller;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@SpringBootTest
@AutoConfigureMockMvc
class TransferControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Test
    void transfer_success() throws Exception {
        String body = "{\"fromAccountId\":\"SAV2001\",\"toAccountId\":\"CUR3001\",\"amount\":25000}";
        mockMvc.perform(post("/api/transfers")
                .contentType(MediaType.APPLICATION_JSON)
                .content(body))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.status").value("SUCCESS"));
        System.out.println("Test passed: transfer succeeded");
    }

    @Test
    void transfer_insufficientBalance() throws Exception {
        String body = "{\"fromAccountId\":\"SAV2001\",\"toAccountId\":\"CUR3001\",\"amount\":999999}";
        mockMvc.perform(post("/api/transfers")
                .contentType(MediaType.APPLICATION_JSON)
                .content(body))
            .andExpect(status().isBadRequest())
            .andExpect(jsonPath("$.error").value("Insufficient balance in SAV2001"));
        System.out.println("Test passed: insufficient balance handled");
    }
}
TEXT
Expected server console output for a successful transfer:
[Filter] ENTER: POST /api/transfers
[Interceptor] preHandle: HandlerMethod
[Controller] transfer: TransferRequest[fromAccountId=SAV2001, toAccountId=CUR3001, amount=25000]
[Service] transfer: SAV2001 -> CUR3001 amount=25000
[Repository] findById: SAV2001
[Repository] findById: CUR3001
[Repository] save: SAV2001 balance=125000.00
[Repository] save: CUR3001 balance=525000.00
[Interceptor] postHandle: controller returned
[Interceptor] afterCompletion: 5ms
[Filter] EXIT: status=200

Expected JSON response:
{"status":"SUCCESS","from":"SAV2001","to":"CUR3001","amount":25000,"fromBalance":125000.00,"toBalance":525000.00}

How to run

BASH
cd bank-lifecycle-demo
mvn clean package -DskipTests
java -jar target/bank-lifecycle-demo-1.0.0.jar

# Test a transfer
curl -X POST http://localhost:8080/api/transfers \
  -H "Content-Type: application/json" \
  -d '{"fromAccountId":"SAV2001","toAccountId":"CUR3001","amount":25000}'

# Test error handling
curl -X POST http://localhost:8080/api/transfers \
  -H "Content-Type: application/json" \
  -d '{"fromAccountId":"SAV2001","toAccountId":"CUR3001","amount":999999}'

mvn test

How does exception handling work in the request lifecycle?

When a controller or service throws an exception, DispatcherServlet catches it in doDispatch() and delegates to HandlerExceptionResolver. The most common resolver is ExceptionHandlerExceptionResolver, which looks for @ExceptionHandler methods in @ControllerAdvice classes.

  • The exception handling flow is:
  • Controller or service throws an exception.
  • DispatcherServlet catches it.
  • HandlerExceptionResolver is called.
  • @ControllerAdvice with @ExceptionHandler matches the exception type.
  • The handler method returns an error response.
  • HttpMessageConverter serializes the error to JSON.
  • Interceptor.afterCompletion still runs (with the exception passed as a parameter).
JAVA
package com.bank;

public class ExceptionHandlingFlow {
    public static void main(String[] args) {
        System.out.println("Exception handling in the request lifecycle:");
        System.out.println("  1. Controller calls service.transfer()");
        System.out.println("  2. Service throws IllegalStateException(\"Insufficient balance\")");
        System.out.println("  3. DispatcherServlet catches the exception");
        System.out.println("  4. ExceptionHandlerExceptionResolver invoked");
        System.out.println("  5. Matches GlobalExceptionHandler.handleBadRequest()");
        System.out.println("  6. Returns Map.of(\"error\", \"Insufficient balance in SAV2001\")");
        System.out.println("  7. Jackson serializes to JSON: {\"error\":\"Insufficient balance...\"}");
        System.out.println("  8. HTTP status: 400 Bad Request");
        System.out.println("  9. Interceptor.afterCompletion() still runs (with exception)");
    }
}
TEXT
Expected output:
Exception handling in the request lifecycle:
  1. Controller calls service.transfer()
  2. Service throws IllegalStateException("Insufficient balance")
  3. DispatcherServlet catches the exception
  4. ExceptionHandlerExceptionResolver invoked
  5. Matches GlobalExceptionHandler.handleBadRequest()
  6. Returns Map.of("error", "Insufficient balance in SAV2001")
  7. Jackson serializes to JSON: {"error":"Insufficient balance..."}
  8. HTTP status: 400 Bad Request
  9. Interceptor.afterCompletion() still runs (with exception)

What are common mistakes in the request lifecycle?

Wrong: doing blocking I/O in a Filter without understanding the impact

JAVA
package com.bank.filter;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SlowFilterWrong implements Filter {
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
                         FilterChain chain) throws IOException, ServletException {
        // WRONG: calling an external API in a filter blocks the Tomcat thread
        // for every request, even health checks
        System.out.println("Calling external auth service...");
        // Thread.sleep(2000); // Simulates slow external call
        chain.doFilter(req, resp);
    }
}
TEXT
Problem: filter runs on every request, including /actuator/health.
Blocking I/O in a filter ties up a Tomcat thread.
With 200 threads and 2 second calls, 200 concurrent requests exhaust the thread pool.

Correct: use an interceptor with path filtering, or make the filter async

JAVA
package com.bank.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuthInterceptorCorrect implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        // Only runs for /api/** paths (configured in WebMvcConfigurer)
        String token = request.getHeader("Authorization");
        if (token == null || !token.startsWith("Bearer ")) {
            response.setStatus(401);
            System.out.println("Auth rejected: missing token");
            return false;
        }
        System.out.println("Auth passed");
        return true;
    }
}
TEXT
Correct: interceptor runs only on /api/** paths.
Health checks and static resources are not affected.
Path filtering is configured in WebMvcConfigurer.addInterceptors().

What should a senior or principal engineer know?

  • Thread model: Tomcat uses a thread pool (default 200 threads in Spring Boot). Each request occupies one thread from Filter entry to response commit. Slow service calls reduce available threads. For high-throughput APIs, consider Spring WebFlux (reactive, non-blocking) or virtual threads (Java 21+, spring.threads.virtual.enabled=true).
  • Content negotiation: DispatcherServlet supports multiple response formats. If the client sends Accept: application/xml, and you have jackson-dataformat-xml on the classpath, the response is XML instead of JSON. Control this with produces = "application/json" on @RequestMapping.
  • Request body caching: by default, the request body InputStream can be read only once. If a filter reads the body (for logging), the controller gets an empty body. Use ContentCachingRequestWrapper to cache the body.
  • Graceful shutdown: Spring Boot 3.x supports graceful shutdown (server.shutdown=graceful). Tomcat stops accepting new connections but finishes in-flight requests within the timeout.
  • Observability: Spring Boot Actuator + Micrometer provide request metrics (http.server.requests) automatically. Each request records method, URI, status, and duration.
JAVA
package com.bank.core;

public class SeniorLifecycleKnowledge {
    public static void main(String[] args) {
        System.out.println("Senior/Principal Request Lifecycle Checklist:");
        System.out.println("  1. Tomcat thread pool: 200 threads default, monitor with /actuator/metrics");
        System.out.println("  2. Virtual threads: spring.threads.virtual.enabled=true (Java 21+)");
        System.out.println("  3. Content negotiation: Accept header + HttpMessageConverter");
        System.out.println("  4. Request body read-once: use ContentCachingRequestWrapper for logging");
        System.out.println("  5. Graceful shutdown: server.shutdown=graceful");
        System.out.println("  6. Observability: Micrometer http.server.requests metric");
        System.out.println("  7. Filter order: @Order(1) runs first, higher number runs later");
    }
}
TEXT
Expected output:
Senior/Principal Request Lifecycle Checklist:
  1. Tomcat thread pool: 200 threads default, monitor with /actuator/metrics
  2. Virtual threads: spring.threads.virtual.enabled=true (Java 21+)
  3. Content negotiation: Accept header + HttpMessageConverter
  4. Request body read-once: use ContentCachingRequestWrapper for logging
  5. Graceful shutdown: server.shutdown=graceful
  6. Observability: Micrometer http.server.requests metric
  7. Filter order: @Order(1) runs first, higher number runs later

What are common interview follow-up questions?

  • What happens if no HandlerMapping matches the request? (DispatcherServlet returns 404 Not Found. If throwExceptionIfNoHandlerFound is set to true, it throws NoHandlerFoundException, which @ControllerAdvice can catch.)
  • How does @RequestBody deserialization work? (RequestMappingHandlerAdapter uses HttpMessageConverter. For JSON, MappingJackson2HttpMessageConverter reads the request body InputStream and uses Jackson ObjectMapper to deserialize it into the method parameter type.)
  • Can you use a different JSON library instead of Jackson? (Yes. Add Gson on the classpath and configure GsonHttpMessageConverter. But Jackson is the default and most widely used.)
  • How does Spring Boot decide between JSON and XML response? (Content negotiation: the Accept header from the client and the produces attribute on @RequestMapping. If the client accepts both, Spring prefers JSON.)
  • What is the difference between @RestController and @Controller + @ResponseBody? (No difference in behavior. @RestController is a shortcut that applies @ResponseBody to all methods.)
  • How does virtual thread support change the request lifecycle? (With virtual threads, each request still gets a thread, but virtual threads are lightweight (managed by the JVM, not the OS). Blocking I/O no longer wastes OS threads. Set spring.threads.virtual.enabled=true in Spring Boot 3.2+.)

Visual Overview

DIAGRAM
 Complete HTTP Request Lifecycle in Spring Boot
 ================================================

 Client
   │
   │  POST /api/transfers
   │  {"fromAccountId":"SAV2001","toAccountId":"CUR3001","amount":25000}
   ▼
 ┌──────────────────────────────────────────────┐
 │ Embedded Tomcat (port 8080)                   │
 │ NIO Connector -> HTTP parsing                 │
 └─────────────────────┬────────────────────────┘
                       ▼
 ┌──────────────────────────────────────────────┐
 │ Servlet Filter Chain                          │
 │  [1] RequestLoggingFilter    ENTER            │
 │  [2] CharacterEncodingFilter                  │
 └─────────────────────┬────────────────────────┘
                       ▼
 ┌──────────────────────────────────────────────┐
 │ DispatcherServlet.doDispatch()                │
 │                                               │
 │  HandlerMapping                               │
 │    -> TransferController.transfer()           │
 │                                               │
 │  TimingInterceptor.preHandle()                │
 │                                               │
 │  HandlerAdapter.handle()                      │
 │    -> Jackson: JSON -> TransferRequest        │
 │    -> TransferController.transfer(request)    │
 │       │                                       │
 │       ▼                                       │
 │    TransferService.transfer()                 │
 │       │                                       │
 │       ▼                                       │
 │    AccountRepository.findById("SAV2001")      │
 │    AccountRepository.findById("CUR3001")      │
 │    AccountRepository.save(SAV2001, 125000)    │
 │    AccountRepository.save(CUR3001, 525000)    │
 │       │                                       │
 │       ▼                                       │
 │    Returns Map{status: SUCCESS, ...}          │
 │                                               │
 │  TimingInterceptor.postHandle()               │
 │                                               │
 │  Jackson: Map -> JSON                         │
 │                                               │
 │  TimingInterceptor.afterCompletion() 5ms      │
 └─────────────────────┬────────────────────────┘
                       ▼
 ┌──────────────────────────────────────────────┐
 │ Servlet Filter Chain (reverse)                │
 │  [2] CharacterEncodingFilter                  │
 │  [1] RequestLoggingFilter    EXIT status=200  │
 └─────────────────────┬────────────────────────┘
                       ▼
 Client receives:
 HTTP/1.1 200 OK
 Content-Type: application/json
 {"status":"SUCCESS","from":"SAV2001",...}

Key Takeaway

When an HTTP request reaches a Spring Boot REST API, it travels through a well-defined pipeline. The embedded Tomcat server receives the TCP connection and parses the HTTP bytes. Servlet Filters handle cross-cutting concerns like encoding and CORS. DispatcherServlet routes the request to the correct controller method through HandlerMapping. HandlerInterceptors run before and after the controller. The controller delegates to the service and repository layers. Jackson serializes the response object to JSON.

In our National Bank of India transfer demo, we traced a POST /api/transfers request through every layer. The RequestLoggingFilter logged entry and exit. The TimingInterceptor measured total processing time. The TransferController received the JSON body as a TransferRequest record. The TransferService validated the balance and updated both accounts. The GlobalExceptionHandler caught insufficient balance errors and returned structured error responses.

The request lifecycle is predictable: Filter -> DispatcherServlet -> Interceptor.preHandle -> Controller -> Service -> Repository -> Interceptor.postHandle -> JSON serialization -> Interceptor.afterCompletion -> Filter -> Client. Exceptions at any layer are caught by DispatcherServlet and routed to @ControllerAdvice.

At the senior level, understand the Tomcat thread model (200 threads default), the option to use virtual threads for better scalability, the request body read-once limitation, and graceful shutdown for zero-downtime deployments.

Remember one sentence: an HTTP request flows through Tomcat, Filters, DispatcherServlet, Interceptors, Controller, Service, Repository, and back through Jackson serialization, with @ControllerAdvice catching exceptions at any layer.

---

Share
Use ← → arrow keys to navigate