原文: http://zetcode.com/spring/pathvariable/

Spring @PathVariable教程显示了如何读取带有@PathVariable注解的 URL 模板变量。 我们创建一个 Spring RESTful 应用来演示注解。

Spring 是用于创建企业应用的流行 Java 应用框架。

@PathVariable

@PathVariable是 Spring 注解,指示方法参数应绑定到 URI 模板变量。 如果方法参数为Map<String, String>,则将使用所有路径变量名称和值填充映射。

它具有以下可选元素:

  • name - 要绑定到的路径变量的名称
  • required - 指示路径变量是否为必需
  • value - 名称的别名

Spring @PathVariable示例

以下示例创建一个使用@PathVariable的 Spring Web 应用。 记录变量值。

  1. pom.xml
  2. src
  3. ├───main
  4. ├───java
  5. └───com
  6. └───zetcode
  7. ├───config
  8. MyWebInitializer.java
  9. WebConfig.java
  10. └───controller
  11. MyController.java
  12. └───resources
  13. logback.xml
  14. └───test
  15. └───java

这是 Spring 应用的项目结构。

pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
  5. http://maven.apache.org/xsd/maven-4.0.0.xsd">
  6. <modelVersion>4.0.0</modelVersion>
  7. <groupId>com.zetcode</groupId>
  8. <artifactId>pathvariableex</artifactId>
  9. <version>1.0-SNAPSHOT</version>
  10. <packaging>war</packaging>
  11. <properties>
  12. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  13. <maven.compiler.source>11</maven.compiler.source>
  14. <maven.compiler.target>11</maven.compiler.target>
  15. <spring-version>5.1.3.RELEASE</spring-version>
  16. </properties>
  17. <dependencies>
  18. <dependency>
  19. <groupId>ch.qos.logback</groupId>
  20. <artifactId>logback-classic</artifactId>
  21. <version>1.2.3</version>
  22. </dependency>
  23. <dependency>
  24. <groupId>javax.servlet</groupId>
  25. <artifactId>javax.servlet-api</artifactId>
  26. <version>4.0.1</version>
  27. <scope>provided</scope>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.springframework</groupId>
  31. <artifactId>spring-webmvc</artifactId>
  32. <version>5.1.3.RELEASE</version>
  33. </dependency>
  34. </dependencies>
  35. <build>
  36. <plugins>
  37. <plugin>
  38. <groupId>org.apache.maven.plugins</groupId>
  39. <artifactId>maven-war-plugin</artifactId>
  40. <version>3.2.2</version>
  41. </plugin>
  42. <plugin>
  43. <groupId>org.eclipse.jetty</groupId>
  44. <artifactId>jetty-maven-plugin</artifactId>
  45. <version>9.4.14.v20181114</version>
  46. </plugin>
  47. </plugins>
  48. </build>
  49. </project>

我们声明项目依赖项。 @PathVariable来自spring-webmvc封装。

resources/logback.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <configuration>
  3. <logger name="org.springframework" level="ERROR"/>
  4. <logger name="com.zetcode" level="INFO"/>
  5. <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender">
  6. <encoder>
  7. <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n
  8. </Pattern>
  9. </encoder>
  10. </appender>
  11. <root>
  12. <level value="INFO" />
  13. <appender-ref ref="consoleAppender" />
  14. </root>
  15. </configuration>

logback.xml是 Logback 日志库的配置文件。

com/zetcode/config/MyWebInitializer.java

  1. package com.zetcode.config;
  2. import org.springframework.context.annotation.Configuration;
  3. import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
  4. @Configuration
  5. public class MyWebInitializer extends
  6. AbstractAnnotationConfigDispatcherServletInitializer {
  7. @Override
  8. protected Class<?>[] getRootConfigClasses() {
  9. return null;
  10. }
  11. @Override
  12. protected Class<?>[] getServletConfigClasses() {
  13. return new Class[]{WebConfig.class};
  14. }
  15. @Override
  16. protected String[] getServletMappings() {
  17. return new String[]{"/"};
  18. }
  19. }

DispatcherServlet是 Spring Web 应用的前端控制器,已注册在MyWebInitializer中。

  1. @Override
  2. protected Class<?>[] getServletConfigClasses() {
  3. return new Class[]{WebConfig.class};
  4. }

getServletConfigClasses()返回 Web 配置类。

com/zetcode/config/WebConfig.java

  1. package com.zetcode.config;
  2. import org.springframework.context.annotation.ComponentScan;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.servlet.config.annotation.EnableWebMvc;
  5. @Configuration
  6. @EnableWebMvc
  7. @ComponentScan(basePackages = {"com.zetcode"})
  8. public class WebConfig {
  9. }

WebConfig通过@EnableWebMvc启用 Spring MVC 注解,并为com.zetcode包配置组件扫描。

com/zetcode/MyController.java

  1. package com.zetcode.controller;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.http.HttpStatus;
  5. import org.springframework.web.bind.annotation.GetMapping;
  6. import org.springframework.web.bind.annotation.PathVariable;
  7. import org.springframework.web.bind.annotation.ResponseStatus;
  8. import org.springframework.web.bind.annotation.RestController;
  9. import java.util.Map;
  10. @RestController
  11. public class MyController {
  12. private static final Logger logger = LoggerFactory.getLogger(MyController.class);
  13. @ResponseStatus(value = HttpStatus.OK)
  14. @GetMapping(value = "/user/{name}")
  15. public void process(@PathVariable String name) {
  16. logger.info("User name: {}", name);
  17. }
  18. @ResponseStatus(value = HttpStatus.OK)
  19. @GetMapping(value = "/user/{name}/{email}")
  20. public void process2(@PathVariable String name, @PathVariable String email) {
  21. logger.info("User name: {} and email: {}", name, email);
  22. }
  23. @ResponseStatus(value = HttpStatus.OK)
  24. @GetMapping(value = "/book/{author}/{title}")
  25. public void process3(@PathVariable Map<String, String> vals) {
  26. logger.info("{}: {}", vals.get("author"), vals.get("title"));
  27. }
  28. }

我们为 GET 请求提供了三个映射。

  1. @ResponseStatus(value = HttpStatus.OK)
  2. @GetMapping(value = "/user/{name}")
  3. public void process(@PathVariable String name) {
  4. logger.info("User name: {}", name);
  5. }

在此代码中,URI 模板变量绑定到name方法参数。

  1. @ResponseStatus(value = HttpStatus.OK)
  2. @GetMapping(value = "/user/{name}/{email}")
  3. public void process2(@PathVariable String name, @PathVariable String email) {
  4. logger.info("User name: {} and email: {}", name, email);
  5. }

通过指定多个@PathVariable注解,也可以绑定多个变量。

  1. @ResponseStatus(value = HttpStatus.OK)
  2. @GetMapping(value = "/book/{author}/{title}")
  3. public void process3(@PathVariable Map<String, String> vals) {
  4. logger.info("{}: {}", vals.get("author"), vals.get("title"));
  5. }

也可以使用Map<String, String>绑定多个变量。

  1. $ mvn jetty:run

我们启动 Jetty 服务器。

  1. $ curl localhost:8080/user/Peter/peter@gmail.com/

我们用curl发出请求。

  1. 22:04:35.273 INFO com.zetcode.controller.MyController - User name: Peter and email: peter@gmail.com

应用记录此消息。

在本教程中,我们使用 Spring 框架创建了一个 RESTful Web 应用。 我们已经演示了@PathVariable的用法。 您可能也对相关教程感兴趣: Spring @RequestMapping教程Spring @RequestHeader教程Java 教程或列出所有 Spring 教程