Java 我可以在 spring 控制器类中使用路径变量吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22980597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 19:44:12  来源:igfitidea点击:

Can I use path variable in spring controller class?

javaspringspring-mvc

提问by Dilip Kumar

Can I use path variable for spring controller class?

我可以为 spring 控制器类使用路径变量吗?

I know that we can use path variables in controller's methods. In the same fashion can we use it for entire class?
Eg:

我知道我们可以在控制器的方法中使用路径变量。我们可以以同样的方式将它用于整个班级吗?
例如:

@Controller
@RequestMapping(value = "{version}/test")
class TestController {

}

Can we use like this? If yes how do we read {version}variable? Actually i need this kind of approach, based on the version i'll respond. If the above approach is not possible can you please suggest me a design to solve this problem?

我们可以这样使用吗?如果是,我们如何读取{version}变量?实际上我需要这种方法,基于我会回应的版本。如果上述方法不可行,您能否建议我一个设计来解决这个问题?

采纳答案by Jan Thom?

Yes you can. Just declare it as @PathVariable in your methods if you want to access it there.

是的你可以。如果您想在那里访问它,只需在您的方法中将其声明为 @PathVariable 即可。

@Controller
@RequestMapping(value = "{version}/test")
class TestController {

    @RequestMapping(value="/something")
    public ModelAndView doSomething(@PathVariable String version) {
       // do something here with the version
    }

}