In a recent project, we faced an interesting challenge: uniformly process incoming HTTP requests to replace multiple possible username fields (e.g., userName, user, gitName, name) in the request body with the actual Git username extracted from the request header. Our initial instinct was to leverage Spring’s familiar Interceptor to handle this pre-processing logic. However, this approach quickly hit a wall.
In this article, I’ll walk you through why the Interceptor failed, why a Servlet Filter became the ideal solution, and the key implementation details to make it work effectively.
1. Problem Scenario and Preliminary Solution
Goal
Our task was straightforward but tricky:
- The request body could be JSON or Form-Data.
- We needed to check for fields like userName, user, gitName, or name.
- If present, these fields should be overwritten with the authenticated Git username (e.g., parsed from a JWT in the Authorization header) to ensure the business logic uses a trusted user identity.