简体   繁体   English

Spring MVC @RequestParam - 多个关键名称? 或另一种要求“一个或另一个”的方式

[英]Spring MVC @RequestParam — multiple key names? or another way to require “one or the other”

What is the best way to allow multiple names for query parameters? 允许多个名称用于查询参数的最佳方法是什么? I have a web service which has changed parameter names, but must continue for a while to accept the old names. 我有一个已更改参数名称的Web服务,但必须继续一段时间才能接受旧名称。

I'm loath to create 2 RequestParams, both not required, b/c I do require one or the other to be present. 我不愿意创建2个RequestParams,两者都不是必需的,b / c我确实需要一个或另一个存在。 Something like this would be sweet: 像这样的东西会很甜蜜:

@RequestParam(value = "startTime|start", required = true ) String startTime,

rather than 而不是

@RequestParam(value = "startTime", required = false ) String startTime,
@RequestParam(value = "start", required = false ) String start ){
if ( start != null || startTime != null ){ //  ... 

Is there any way to do this? 有没有办法做到这一点? Thanks. 谢谢。

You can do something like this (create a proxy method that will intercept the "old" calls and transfer them to the new method): 你可以做这样的事情(创建一个代理方法,拦截“旧”调用并将它们转移到新方法):

@RequestMapping(value="/your-mapping", params = {"oldparam1", "oldparam2", ...})
public Whatever yourOldMethod(@RequestParam(value="oldparam1", required=true) String oldParam1, ...){
   return yourNewMethod(oldParam1, ...);
}

@RequestMapping(value="/your-mapping", params = {"newparam1", "newparam1", ...})
public Whatever yourNewMethod(@RequestParam(value="newparam1", required=true) String oldParam1, ...){
   //do whatever you need to do here
}

When you don't need to support the old calls, simply delete yourOldMethod . 如果您不需要支持旧呼叫,只需删除yourOldMethod

The beauty here, is using the "params" of @RequestMapping , thus allowing 2 methods to listen to the same "URL" (with different params for each) 这里的美丽是使用@RequestMapping"params" ,因此允许2种方法听同一个"URL" (每个都有不同的参数)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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