It's more suitable to do that inside a Spring Filter(an interceptor).To store the retrieved value in order to use it later in the controller or service part, consider using a Spring bean with the Scope request(request scope creates a bean instance for a single HTTP request).
Below the interceptor code example:
@Component
public class RequestInterceptor implements Filter {
private final RequestData requestData;
public RequestInterceptor(RequestInfo requestInfo) {
this.requestInfo = requestInfo;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
//Get authorization
var authorization = request.getHeader(HttpHeaders.AUTHORIZATION);
//Get some path variables
var pathVariables = request.getHttpServletMapping().getMatchValue();
var partyId = pathVariables.substring(0, pathVariables.indexOf('/'));
//Store in the scoped bean
requestInfo.setPartyId(partyId);
filterChain.doFilter(servletRequest, servletResponse);
}
}
For safe access of the storing value in the RequestData
bean, I advise to always use a ThreadLocal construct to hold the managed value:
@Component
@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class RequestData {
private final ThreadLocal<String> partyId = new ThreadLocal<>();
public String getPartyId() {
return partyId.get();
}
public void setPartyId(String partyId) {
this.partyId.set(partyId);
}
}