How can I create a URL based on controller and action method in Spring MVC?

后端 未结 4 1525
情歌与酒
情歌与酒 2020-12-17 17:38

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

相关标签:
4条回答
  • 2020-12-17 17:45

    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!)

    0 讨论(0)
  • 2020-12-17 17:50

    For a long time I have thought about implementing something like this using CGLib proxies but was too lazy. It appears Spring HATEOS library will allow you to do it the proxy way I wnated to and variety of other ways.

    0 讨论(0)
  • 2020-12-17 17:53

    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() { ... }
    
    0 讨论(0)
  • 2020-12-17 17:53

    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.

    0 讨论(0)
提交回复
热议问题