[英]How can I create a URL based on controller and action method in Spring MVC?
I am using Spring MVC 3.0 我正在使用Spring MVC 3.0
I have a guestbook.jsp page where I want to create a link that points to GuestBookController's login method. 我有一个guestbook.jsp页面,我想创建一个指向GuestBookController的登录方法的链接。
This is a simple task that most web frameworks handle this (eg grails does it with g:link tag) but I couldn't find any documentation on this in the official SpringMVC docs. 这是一个简单的任务,大多数Web框架都可以处理这个问题(例如Grails用g:link标签完成)但我在官方的SpringMVC文档中找不到任何关于此的文档。
So I am scratching my head - Is this functionality in some tag library? 所以我在摸不着头脑 - 这个功能在某些标签库中吗? Does the framework expose it?
框架是否暴露了它? Do I have to extend the framework to get this to work?
我是否必须扩展框架才能使其工作?
Note, I am not taking about hardcoding the url (which is an obvious but weak solution) but rather generating it based on controller and action name. 注意,我没有采取硬编码url(这是一个明显但很弱的解决方案),而是基于控制器和动作名称生成它。
UPDATE : Spring MVC doesn't provide this functionality. 更新 :Spring MVC不提供此功能。 There is a JIRA ticket though.
虽然有一张JIRA票。 You can vote here https://jira.springsource.org/browse/SPR-5779
你可以在这里投票https://jira.springsource.org/browse/SPR-5779
The short answer is no, you can't do this with Spring MVC currently. 简短的回答是否定的,目前你不能用Spring MVC做到这一点。
It's a shame because you can do this in other frameworks including Grails (which uses Spring MVC under the hood). 这很遗憾,因为您可以在其他框架中执行此操作,包括Grails(在引擎盖下使用Spring MVC)。
See the discussion here which includes a link to a Spring feature request to add this (vote for it!) 请参阅此处的讨论,其中包含添加此功能的Spring功能请求的链接(投票支持!)
Spring MVC uses the standard JSTL tags in JSPs so: Spring MVC在JSP中使用标准的JSTL标记,因此:
<c:url value="/guestBook.html" var="guestBookLink" />
<a href="${guestBookLink}">Guest Book</a>
In your controller: 在你的控制器中:
@RequestMapping(value = "/guestBook")
public String handleGuestBook() { ... }
For a long time I have thought about implementing something like this using CGLib proxies but was too lazy. 很长一段时间以来,我一直在考虑使用CGLib代理实现类似的东西,但是太懒了。 It appears Spring HATEOS library will allow you to do it the proxy way I wnated to and variety of other ways.
看来, Spring HATEOS库将允许您以我所知的代理方式和其他各种方式来实现。
Annotate your login method with @RequestMapping, like so: 使用@RequestMapping注释您的登录方法,如下所示:
@Controller
public class GuestBookController {
...
@RequestMapping(value="/mycontextroot/login", method = RequestMethod.GET)
public String login() {
...
}
...
}
Then, in your JSP, create a link something like this: 然后,在JSP中,创建如下链接:
<c:url var="loginlink" value="/mycontextroot/login.html">
</c:url>
<a href="${loginlink}">Login</a>
This assumes that your dispatcher servlet is looking for *.html URLs. 这假设您的调度程序servlet正在查找* .html URL。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.