在Spring MVC控制器硬件codeD @RequestMapping网址 [英] Hard-coded @RequestMapping URL in Spring MVC Controller
问题描述
我学习春天3,我用它在一个简单的Web应用程序。
I'm studying Spring 3 and I'm using it in a simple web-application.
现在我使用注解来实现一个Spring MVC的控制器,我想知道:
有没有使用 @RequestMapping
标注任何的最佳做法?
Now I'm implementing a Spring MVC Controller using annotations, and I'm wondering:
Is there any best practice using @RequestMapping
annotation?
我的意思是:我已经看到,一般在此注释中映射的URL是在级硬盘$ C $ ... CD
有没有办法通过URL在松散耦合的方式(获得更可重用的类)?
I mean: I've seen that usually the URL mapped in this annotation is hardcoded in the class...
Is there a way to pass the URL in a 'loosely coupled way' (to obtain a more reusable class)?
我知道有的,可用于一些的外卡,但我认为这不是解决办法...难道我错了吗?
I know that there are some wild cards that can be used, but I think that isn't the solution... Am I wrong?
编辑:
我添加了一个例子来更好地解释我的疑问。
I add an example to better explain my doubt.
假设我希望我的控制器由请求触发到 /foo/bar/baz/mypage.htm
,在我的控制器的处理方法将与<注解code> @RequestMapping(/富/酒吧/巴兹/我的空间')。
Suppose I want my controller to be triggered by a request to /foo/bar/baz/mypage.htm
, in my controller the handler method will be annotated with @RequestMapping("/foo/bar/baz/mypage")
.
现在我决定改变URL触发我的控制器到 /foo/bar/otherpage.htm
,所以我需要编辑我的课,把 @RequestMapping(/富/酒吧/ otherpage)
我的处理方法,重新编译项目,然后重新部署它。
Now I decide to change the URL triggering my controller into /foo/bar/otherpage.htm
, so i need to edit my class, put @RequestMapping("/foo/bar/otherpage")
on my handler method, recompile the project and deploy it again.
在我看来不是那么实用...
It seems to me not so practical...
推荐答案
目前注解控制器都不是很可配置的。
Currently annotated controllers aren't very configurable.
据我所知,唯一可行的办法解决这个问题是使用替代<一个href=\"http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/web/servlet/HandlerMapping.html\"相对=nofollow> 的HandlerMapping
取值为了配置控制器的基本URL。例如,如下所示:
As far as I know, the only possible approach to this problem is to use alternative HandlerMapping
s in order to configure "base URLs" of controllers. For example, as follows:
// Note the absense of @Controller to prevent this controller
// from being discovered by DefaultAnnotationHandlerMapping
public class FooController {
@RequestMapping("/list") public String list(...) { ... }
@ReqeustMapping("/save") public String save(...) { ... }
}
。
<bean
class = "org.springframework.web.servlet.mvc.support.ControllerBeanNameHandlerMapping" />
<bean name = "/foo" class = "FooController" />
<bean name = "/bar" class = "FooController" />
在这个例子中 FooController的
处理 /富/列表
, /富的两个实例/保存
, /酒吧/列表
键,分别为 /酒吧/保存
。
In this example two instances of FooController
handle /foo/list
, /foo/save
, /bar/list
and /bar/save
respectively.
即将举行春季3.1将有一个改进的弹簧3.1架构(的春3.1 M2:Spring MVC的增强),这似乎是更灵活,虽然我还没有检查它尚未
The upcoming Spring 3.1 will have an improved Spring 3.1 architecture (Spring 3.1 M2: Spring MVC Enhancements) that seems to be more flexible, though I haven't checked it yet.
这篇关于在Spring MVC控制器硬件codeD @RequestMapping网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!