14

I am using Spring MVC 3.0

I have a guestbook.jsp page where I want to create a link that points to GuestBookController's login method.

This is a simple task that most web frameworks handle this (e.g grails does it with g:link tag) but I couldn't find any documentation on this in the official SpringMVC docs.

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.

UPDATE: Spring MVC doesn't provide this functionality. There is a JIRA ticket though. You can vote here https://jira.springsource.org/browse/SPR-5779

4 Answers4

9

The short answer is no, you can't do this with Spring MVC currently.

It's a shame because you can do this in other frameworks including Grails (which uses Spring MVC under the hood).

See the discussion here which includes a link to a Spring feature request to add this (vote for it!)

Community
  • 1
  • 1
sourcedelica
  • 23,940
  • 7
  • 66
  • 74
3

Spring MVC uses the standard JSTL tags in JSPs so:

<c:url value="/guestBook.html" var="guestBookLink" />
<a href="${guestBookLink}">Guest Book</a>

In your controller:

@RequestMapping(value = "/guestBook")
public String handleGuestBook() { ... }
Abdullah Jibaly
  • 53,220
  • 42
  • 124
  • 197
2

The Spring HATEOS library provides an API to generate links to MVC controller methods in various ways.

For example:

URI url = linkTo(methodOn(GuestBookController.class).login()).toUri();
OrangeDog
  • 36,653
  • 12
  • 122
  • 207
Adam Gent
  • 47,843
  • 23
  • 153
  • 203
0

Annotate your login method with @RequestMapping, like so:

@Controller
public class GuestBookController {
  ...
  @RequestMapping(value="/mycontextroot/login", method = RequestMethod.GET)
  public String login() {
    ...
  }
  ...
}

Then, in your JSP, create a link something like this:

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

GriffeyDog
  • 8,186
  • 3
  • 22
  • 34