Spring + JSP url构建最佳实践

Den*_*nov 14 spring jsp spring-mvc

我想知道在JSP中解决Spring控制器是否有任何好的做法.

假设我有控制器:

@Controller
class FooController {

  // Don't bother about semantic of this query right now
  @RequestMapping("/search/{applicationId}")
  public String handleSearch(@PathVariable String applicationId) {
    [...]
  }
}
Run Code Online (Sandbox Code Playgroud)

当然在JSP中我可以写:

<c:url value="/search/${application.id}" />
Run Code Online (Sandbox Code Playgroud)

但是现在很难改变网址.如果您熟悉Rails/Grails,那么现在您可以解决此问题:

redirect_to(:controller => 'foo', :action = 'search')
Run Code Online (Sandbox Code Playgroud)

但是在Spring中有很多UrlMappers.每个UrlMapper都有自己的语义和绑定方案.Rails一样的方案根本不起作用(除非你自己实现).我的问题是:在Spring中有没有更方便的方法来解决JSP中的控制器问题?

Jan*_*ing 10

我希望我理解你的问题.我想你的问题是当url字符串在jsp和控制器映射中时如何维护url.

你的Controller应该做逻辑,你的JSP应该做输出.构建Url应该是处理它的控制器的责任.所以

class SearchController {

  @RequestMapping("/search/{applicationId}")
  public String handleSearch(@PathVariable String applicationId) {
    [...]
  }

  public String getUrl(Long applicationId) {
      return "/search/" + applicationId;
  }
}

class StartController {
   private SearchController controller;

   @ModelAttribute("searchUrl")
   public String getSearchUrl() {
       return fooController.getUrl(applicationId);
   }
}
Run Code Online (Sandbox Code Playgroud)

并在你的start.jsp做

 <c:url value="${searchUrl}" />
Run Code Online (Sandbox Code Playgroud)