在 Spring MVC 中使用 URL 的一部分作为控制器的参数
例如,URL
foo.com/bar/99
99 将可直接作为参数提供给控制器中的方法。控制器映射到 /bar
对于任何熟悉 ASP.NET MVC 或 Django 的人来说,这类似于前者中的routes.MapRoute 和后者中的 urlpatterns 中使用 (?P\d+) 。
可以直接处理 Http Request 对象中的数据来获取此数据,但我想知道 Spring MVC 是否对此有内置支持(特别是 2.5 版本)。
For example, with the URL
foo.com/bar/99
99 will be available directly to a method in the controller as an argument. The controller is mapped to /bar
For anyone familiar with ASP.NET MVC or Django, this would be similar to routes.MapRoute in the former and using (?P\d+) in urlpatterns in the latter.
It would be possible to process the data in the Http Request object directly to get this, but I'd like to know if Spring MVC has built-in support for this (particularly version 2.5).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于使用 Spring 3 的任何人,我了解到这可以使用新的 @PathVairable 注释来完成,
这是来自 http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/
For anyone using Spring 3, I've learned this can be done using the new @PathVairable annotation
Here's the example from http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/
不,Spring 不支持开箱即用。但是,您可以使用 @RequestMapping 并适当配置
InternalPathMethodNameResolver
:您必须为
InternalPathMethodNameResolver< 指定
前缀
/code> 作为“do”以使上述工作正常,因为方法名称不能以数字开头。如果您使用“foo.com/bar/baz”作为 URL 并调用您的方法baz
,则不需要额外的配置。如果您不想使用方法名称映射,则获取“99”作为参数就像从方法中的
request.getPathInfo()
中获取它一样简单。No, Spring does not support this out of the box. You can, however, map path to method name using @RequestMapping and appropriately configured
InternalPathMethodNameResolver
:You'll have to specify
prefix
forInternalPathMethodNameResolver
as "do" for the above to work since method names can't begin with digit. If you were to use "foo.com/bar/baz" as URL and call your methodbaz
, no additional configuration would be necessary.If you don't want to use method name mapping, getting '99' as parameter is as easy as grabbing it from
request.getPathInfo()
in your method.