找到你要的答案

Q:Spring MVC, links to controller in JSP, and DRY principle

Q:Spring MVC控制器,JSP中的链接,和干燥的原理

I have a Spring MVC application with hundreds of controllers. In the controllers I use the usual @Requestmapping mappings:

@RequestMapping(value="/someUrl.go")
public String myMethod () {
    // implementation here;
}

Now, in the JSP page, I build a link to another page like this:

<a href="someUrl.go">Link to another page</a>

The problem: the relative URL of the target page, "someUrl.go", and other hundreds like it, are written twice in my application - once in the annotation and once in the JSP that links to it. Actually, some pages are linked to from more than one JSP, so their URL is written many times.

Does Spring MVC offer any solution for this? Ideally, I'd like some reverse mapping with all the URLs that Spring MVC is aware of, and a unique name for each of them, so I can use that name in the JSP to obtain the URL instead of hard-coding it.

Update: this seems like a duplicate of How can I create a URL based on controller and action method in Spring MVC?, except that in the other question they ask about Spring MVC 3. In Spring 4 this problem is solved, as shown here (https://jira.spring.io/browse/SPR-5779)

我有成百上千的Spring MVC应用控制器。在控制器的使用通常的“requestmapping映射:

@RequestMapping(value="/someUrl.go")
public String myMethod () {
    // implementation here;
}

现在,在JSP页面中,我建立了一个链接到另一个页面,这样:

<a href="someUrl.go">Link to another page</a>

问题:目标页面的URL,相对“someurl。走”,和其他成百上千的喜欢,都写在我的申请两次-一次在注释和曾经在JSP链接到它。实际上,一些页面链接到多个JSP,所以他们的网址是写过很多次。

这是Spring MVC提供任何解决方案?理想的情况下,我想所有的Spring MVC知道URL一些反向映射,并为他们的每一个独特的名字,所以我可以使用JSP,名字取得代替硬编码的URL。

更新:这似乎是一个重复的我如何创建一个URL基于Spring MVC的控制器和动作方法?,除其他问题他们问Spring MVC 3。在4的春天,这个问题解决了,如图所示(https://jira.spring.io/browse/spr-5779)

answer1: 回答1:

I found the solution, it is explained here (https://jira.spring.io/browse/SPR-5779). The JSP code looks like this:

<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>

<a href="${s:mvcUrl('AC#myMethod').build()}">Link to another page</a>

Where AC are the camel-case initials of my controller class. If there are conflicts because controllers have similar names, it is possible to assign a name explicitly to each annotated method, like this:

@RequestMapping ( name = "myName", value= ...)

I found the solution, it is explained here (https://jira.spring.io/browse/SPR-5779). The JSP code looks like this:

<%@ taglib uri="http://www.springframework.org/tags" prefix="s" %>

<a href="${s:mvcUrl('AC#myMethod').build()}">Link to another page</a>

AC是我的控制器类骆驼实例的缩写。如果有冲突,因为控制器有相似的名称,可以给每个注释的方法显式指定一个名称,像这样:

@RequestMapping ( name = "myName", value= ...)
spring-mvc