132.md 3.5 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4
# Spring 中的 PathVariable 注释

> 原文: [https://javatutorial.net/pathvariable-annotation-in-spring](https://javatutorial.net/pathvariable-annotation-in-spring)

W
wizardforcel 已提交
5
就像@RequestParam 一样,@PathVariable 注解用于从 HTTP request 中提取数据。 但是,它们略有不同。 区别在于@RequestParam 从 URL 获取参数,而@PathVariable 只是从 URI 中提取参数。
W
init  
wizardforcel 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45

![java-featured-image](img/e0db051dedc1179e7424b6d998a6a772.jpg)

### 例

假设您有一个支持以下 URL 的网站:

```java
http://www.yourwebsite.net/employee/1
```

上面的 URL 中的 **1** 代表员工的 ID。 到目前为止,一切都很好。 现在,从您的 Spring 控制器开始,路径看起来像(取决于您给 id 赋予的名称):

```java
/employee/{id}
```

以上网址路径对我们有何帮助? 好吧,由于有了{}语法(碰巧称为 URI 模板),您现在可以使用@PathVariable 将其传递给方法,并且您的方法以及注释将类似于以下内容:

```java
@RequestMapping(value="/employee/{id}", method=RequestMethod.GET)
<Access Modifier> <Return Type> <Method Name> (@PathVariable <Type> id) { <body> }
```

从上面的代码片段中可以看到,现在“ id”将从路径中引用{id}。 让我们尝试一个真实的例子:

```java
@Controller
@SpringBootApplication
public class EmployeeManager {
   @RequestMapping(value=" /employee/{id}")
   public String pathVariableDemo(Model model, @PathVariable int id) {
      model.addAttribute("id", id);
      return "demo";
   }
}
```

现在,Spring 查看 out id 参数,并将其与模板变量“ id”进行匹配。

W
wizardforcel 已提交
46
请记住,如果我的代码将“ id”(参数)命名为其他名称,则将无法使用。 但是,如果您不想为参数和模板变量使用相同的名称,则可以指定 PathVariable 注解的名称,如下所示:
W
init  
wizardforcel 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64

```java
@Controller
@SpringBootApplication
public class EmployeeManager {
   @RequestMapping(value=" /employee/{id}")
   public String pathVariableDemo(Model model, @PathVariable("id") int someRandomName) {
      model.addAttribute("id", someRandomName);
      return "demo";
   }
}
```

从上面的示例中可以看到,我将参数名称更改为 someRandomName ,但我还添加了@PathVariable **(“ id”)**,它再次指定了我们要引用的模板变量 至。

因此,最终您有两个选择:

1.  方法参数使用相同的名称
W
wizardforcel 已提交
65
2.  在@PathVariable 注解中指定模板变量的名称
W
init  
wizardforcel 已提交
66

W
wizardforcel 已提交
67
### 多个@PathVariable 注解
W
init  
wizardforcel 已提交
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96

如果您可以有多个@PathVariable,该怎么办? 我们可以做到吗? 我们可以! 实际上,这与添加单个@PathVariable 非常相似。

我来给你展示。

```java
@Controller
@SpringBootApplication
public class EmployeeManager {
   @RequestMapping(value="/{company}/employee/{id}", method=RequestMethod.GET)
   public String pathVariableDemo(@PathVariable("company") String companyName, @PathVariable("id") int employeeId) {
      // handle the code
      return "demo";
   }
}
```

从上面的代码片段中可以看到,我们有两个模板变量:

1.  **公司**
2.  **ID**

然后,我们提取每个模板变量,然后通过指定方法参数所引用的临时变量将它们“分配”给方法参数。

## @PathVariable vs @RequestParam 结论

尽管@PathVariable 和@RequestParam 都用于从 URL 提取值,但是可以根据 URL 的设计使用它们。

通常,@ PathVariable 通常用于 RESTful Web 服务中,而@RequestParam 用于从查询参数中提取数据。