简体   繁体   中英

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

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) {}

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

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