Skip to main content
 首页 » 编程设计

spring中Spring中是否有像rails中那样通过id进行路由的概念

2024年11月24日14EasonJim

如果我想获得Office's在 Rails 中显示页面,我只需使用 url .../offices/:id

我有一个 Spring 应用程序,我正在尝试实现同样的事情。我不知道如何编写一个 href 来访问 office's showOffice页。我有一个 Controller 方法:

@RequestMapping(value = "/showOffice", method=RequestMethod.GET)  
    public ModelAndView showOfficePage(Long officeId) { 
        Office office = officeServiceImpl.find(officeId); 
        ModelAndView result = new ModelAndView("showOffice", "command", office); 
        return result; 
    } 

我唯一能想到的是<a href="${pageContext.request.contextPath}/showOffice(${10})" class="btn btn-primary btn-lg" role="button">

有人能指出我正确的方向吗?谢谢。

请您参考如下方法:

是的。 Spring 3.0 及更高版本支持 @PathVariable 注解来解决这种情况。请参阅docs欲了解更多信息。

@RequestMapping(value = "/offices/{officeId}", method=RequestMethod.GET)  
public ModelAndView showOfficePage(@PathVariable("officeId") Long officeId) { 
    Office office = officeServiceImpl.find(officeId); 
    ModelAndView result = new ModelAndView("showOffice", "command", office); 
    return result; 
} 

普通的串联将有助于在您的 View 中构建这些 URL:

<a href="/offices/<%= offices.id %>" >Link</a>