简体   繁体   中英

How to enrich the message headers with uri variables or parameters in Spring Integration java dsl

I'm trying to enrich the headers of the messages coming from an http inbound gateway ; my uri looks like this:

requestMapping.setPathPatterns("/context/{fooId}");

But I don't know how to use the setHeaderExpressions method of the HttpRequestHandlingMessagingGateway to catch the uri variable and put its value in the header.

I have no more success with the .enrichHeaders(...) since this code generates an exception:

IntegrationFlows.from(requestNotificationChannel())
  .enrichHeaders(h -> h.header("fooId", "#pathVariables.fooId")

What is the good way to extract the values from the uri-variables and/or from the parameters ?

Thanks !

Well, you missunderstood a bit how HttpRequestHandlingMessagingGateway works or we missed something in the documentaiton.

Each SpEL evaluation is done withing EvaluationContext and it is fresh for each component. The #pathVariables EvaluationContext varialbe is available only from the HttpRequestHandlingMessagingGateway during request processing. Other similar variables from the request and available for message building from the HttpRequestHandlingMessagingGateway are:

  • requestAttributes
  • requestParams
  • requestHeaders
  • cookies
  • matrixVariables

What I want to say that it doesn't work for regular .enrichHeaders() because it uses a new fresh EvaluationContext and all those variable aren't available already. That's why HttpRequestHandlingMessagingGateway provides setHeaderExpressions . and here is a sample how to use it for you case:

private final static SpelExpressionParser PARSER = new SpelExpressionParser();
....
@Bean
public HttpRequestHandlingMessagingGateway httpInboundGateway() {
     ....
     httpInboundGateway.setHeaderExpressions(Collections.singletonMap("fooId", PARSER.parseExpression("#pathVariables.fooId")));
     ....
}

From other side, if your requestNotificationChannel() is DirectChannel , you don't leave the HTTP Request Thread in the .enrichHeaders() , therefore you can do something like this:

.enrichHeaders(h -> h.headerFunction("fooId", m ->
                        ((Map<String, String>) RequestContextHolder.currentRequestAttributes()
                                        .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, 0)).get("fooId")))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM