1
votes

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)

1
Let me understand your intentions... You don't want to write links, but you want to add another layer of abstraction and write link identifiers instead of the links themselves. Seems like "less music for more money" to me.Pavel Horal
I want exactly that, and it not less music for more money, it is more music :) actually, I found the solution here: jira.spring.io/browse/SPR-5779 and here: stackoverflow.com/questions/6022980/…Yoni
That is quite interesting and something I didn't know exists... nice find.Pavel Horal

1 Answers

2
votes

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= ...)