Spring mvc @PathVariable

127
你能为我简要解释一下在Spring MVC中如何使用@PathVariable并提供一个示例吗?请包括如何键入URL。
我正在努力获得正确的URL以显示JSP页面。谢谢。

2
通过Spring MVC控制器显示JSP是通过视图或称为“ModelAndView”完成的。@PathVariable注释用于在控制器端获取变量名称及其值。例如:www.abcd.com/api/value=34455&anotherValue=skjdfjhks,这里的**value**和**anotherValue**是变量,您可以使用@PathVariable("value") int value和@PathVariable("anotherValue")String anotherValue来获取它们。 - Aman Gupta
8个回答

222
假设你想编写一个用于获取某个订单的网址,可以这样说:
www.mydomain.com/order/123

其中123是orderId。

现在在Spring MVC控制器中使用的URL将如下所示

/order/{orderId}
现在订单ID可以声明为路径变量。
@RequestMapping(value = " /order/{orderId}", method=RequestMethod.GET)
public String getOrder(@PathVariable String orderId){
//fetch order
}

如果您使用的URL是www.mydomain.com/order/123,则Spring会将orderId变量填充为值123。

另外请注意,PathVariable与requestParam不同,因为PathVariable是URL的一部分。 使用请求参数的相同URL将如下所示:www.mydomain.com/order?orderId=123

API文档
Spring官方参考文档


在使用pathVariable时,我需要导入什么东西吗?或者任何依赖关系吗?谢谢。 - james
你只需要导入PathVariable注解 import org.springframework.web.bind.annotation.PathVariable。 - coder
请提供一些细节,您想要做什么以及遇到了什么问题。 - coder
http://stackoverflow.com/questions/19804202/pathvariable-location-spring-mvc.. 这里是代码 - james
你可以使用 @PathVariable int orderId,如果传递的值是有效的整数,Spring 将自动管理转换。 - coder

10

请看下面的代码片段。

@RequestMapping(value="/Add/{type}")
public ModelAndView addForm(@PathVariable String type) {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("addContent");
    modelAndView.addObject("typelist", contentPropertyDAO.getType() );
    modelAndView.addObject("property", contentPropertyDAO.get(type,0) );
    return modelAndView;
}

希望它能帮助你构建代码。


我不熟悉模型和视图。呵呵。顺便说一下,谢谢..期待在我的项目中实现它..但我需要先完成它。 :) - james
我认为你需要写@PathVariable("type")来绑定路径。 - FelixM
1
理解了,使用正则表达式[a-zA-z0-9.]。 - prem30488

8

如果您有带有路径变量的URL,例如www.myexampl.com/item/12/update,其中12是ID,create是您要用于指定执行的变量,例如使用单个表单进行更新和创建,您可以在控制器中执行此操作。

   @PostMapping(value = "/item/{id}/{method}")
    public String getForm(@PathVariable("id") String itemId ,  
        @PathVariable("method") String methodCall , Model model){

     if(methodCall.equals("create")){
            //logic
      }
     if(methodCall.equals("update")){
            //logic
      }

      return "path to your form";
    }

此机制确保路径变量与特定变量绑定。 - ochiWlad

2

@PathVariable用于从URL中获取值。

例如:要获取某个问题,可以使用如下代码:

www.stackoverflow.com/questions/19803731

这里有一个问题,id作为URL的参数传递。

现在,在controller中获取这个值,你只需在方法参数中传递@PathVariable即可。

@RequestMapping(value = " /questions/{questionId}", method=RequestMethod.GET)
    public String getQuestion(@PathVariable String questionId){
    //return question details
}

这个表单长什么样子?我能用其中一个输入值来指定{ISBN}值吗?如果可以,我该如何构建完整的URL以用于表单参数th:action? - Jan Horčička

1

注解表示方法参数应绑定到URI模板变量。支持RequestMapping注释的处理程序方法。

@RequestMapping(value = "/download/{documentId}", method = RequestMethod.GET)
public ModelAndView download(@PathVariable int documentId) {
    ModelAndView mav = new ModelAndView();
    Document document =  documentService.fileDownload(documentId);

    mav.addObject("downloadDocument", document);
    mav.setViewName("download");

    return mav;
}

0
假设您使用的url是www.example.com/test/111。 现在,您需要将值111(动态值)传递到控制器方法中。这时,您可以使用@PathVariable注释来完成操作:
@RequestMapping(value = " /test/{testvalue}", method=RequestMethod.GET)
public void test(@PathVariable String testvalue){
//you can use test value here
}

因此,变量值从URL中检索出来。


0

这是用于映射/处理动态URI的注释之一。您甚至可以为URI动态参数指定正则表达式,以仅接受特定类型的输入。

例如,如果检索使用唯一编号的书籍的URL如下:

URL:http://localhost:8080/book/9783827319333

可以使用@PathVariable获取URL末尾表示的数字,如下所示:

@RequestMapping(value="/book/{ISBN}", method= RequestMethod.GET)

public String showBookDetails(@PathVariable("ISBN") String id,

Model model){

model.addAttribute("ISBN", id);

return "bookDetails";

}

简而言之,这只是在Spring中从HTTP请求中提取数据的另一种方法。

这个表单长什么样子?我能用其中一个输入值来指定{ISBN}值吗?如果可以,我该如何构建完整的URL以用于表单参数th:action? - Jan Horčička

-1
请看下面的代码片段。
@RequestMapping(value = "edit.htm", method = RequestMethod.GET) 
    public ModelAndView edit(@RequestParam("id") String id) throws Exception {
        ModelMap modelMap = new ModelMap();
        modelMap.addAttribute("user", userinfoDao.findById(id));
        return new ModelAndView("edit", modelMap);      
    }

如果您想查看完整的项目并了解其工作原理,请从以下链接下载:

GitLab上的UserInfo项目


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接