yosi
yosi

Reputation: 897

Spring mvc mapping headers and parameters

I would like to support a scenario where a specific piece of value can be sent to my application either by a parameter or header. I have several arguments that I would like to support in this fashion.

What would be the best approach to achieve this with Spring mvc annotations?

Please note that sometimes the header will me sent to me and sometimes a parameter with the same key. From my application perspective it makes no difference at all. The best way for me would be to map it to a JavaBean.

Is it possible?

Yosi

Upvotes: 1

Views: 1806

Answers (2)

Bozho
Bozho

Reputation: 597026

The best option is to have a custom WebArgumentResolver. Then you can annotate the param with, say, @ParamOrHeader. See an exmmple here How to pass a session attribute as method argument (parameter) with Spring MVC . It is about a session attribute, but it will be simple to change it for param-or-header

Upvotes: 2

Igor Artamonov
Igor Artamonov

Reputation: 35961

You can also map both of them an use first non-empty. Like:

ModelAndView methodDispatcher(@RequestParam(value = "X-Param", defaultValue = "") string header, @RequestParam(value = "param", defaultValue = "") string param) {
    if (StringUtils.isNotEmpty(param)) {
       return method(param);
    }
    if (StringUtils.isNotEmpty(header)) {
       return method(header);
    }
    throw BadRequestException();
}

ModelAndView method(String param) {}

Upvotes: 3

Related Questions