Spring @PathVariable 教程显示了如何读取带有@PathVariable注解的 URL 模板变量。 我们创建一个 Spring RESTful 应用来演示注释。
Spring 是用于创建企业应用的流行 Java 应用框架。
@PathVariable
@PathVariable 是 Spring 注释,指示方法参数应绑定到 URI 模板变量。 如果方法参数为Map<String, String>,则将使用所有路径变量名称和值填充映射。
它具有以下可选元素:
name-要绑定到的路径变量的名称required-指示路径变量是否为必需值-名称的别名Spring @PathVariable示例
以下示例创建一个使用@PathVariable的 Spring Web 应用。 记录变量值。
pom.xmlsrc├───main│ ├───java│ │ └───com│ │ └───zetcode│ │ ├───config│ │ │ MyWebInitializer.java│ │ │ WebConfig.java│ │ └───controller│ │ MyController.java│ └───resources│ logback.xml└───test └───java
这是 Spring 应用的项目结构。
pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zetcode</groupId> <artifactId>pathvariableex</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> <spring-version>5.1.3.RELEASE</spring-version> </properties> <dependencies> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.3.RELEASE</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>9.4.14.v20181114</version> </plugin> </plugins> </build></project>
我们声明项目依赖项。 @PathVariable来自spring-webmvc封装。
resources/logback.xml
<?xml version="1.0" encoding="UTF-8"?><configuration> <logger name="org.springframework" level="ERROR"/> <logger name="com.zetcode" level="INFO"/> <appender name="consoleAppender" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <Pattern>%d{HH:mm:ss.SSS} %blue(%-5level) %magenta(%logger{36}) - %msg %n </Pattern> </encoder> </appender> <root> <level value="INFO" /> <appender-ref ref="consoleAppender" /> </root></configuration>logback.xml是 Logback 日志库的配置文件。
com/zetcode/config/MyWebInitializer.java
package com.zetcode.config;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;@Configurationpublic class MyWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return null; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; }}DispatcherServlet是 Spring Web 应用的前端控制器,已注册在MyWebInitializer中。
@Overrideprotected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class};}getServletConfigClasses()返回 Web 配置类。
com/zetcode/config/WebConfig.java
package com.zetcode.config;import org.springframework.context.annotation.ComponentScan;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.EnableWebMvc;@Configuration@EnableWebMvc@ComponentScan(basePackages = {"com.zetcode"})public class WebConfig {}WebConfig通过@EnableWebMvc启用 Spring MVC 注解,并为com.zetcode软件包配置组件扫描。
com/zetcode/MyController.java
package com.zetcode.controller;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpStatus;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.ResponseStatus;import org.springframework.web.bind.annotation.RestController;import java.util.Map;@RestControllerpublic class MyController { private static final Logger logger = LoggerFactory.getLogger(MyController.class); @ResponseStatus(value = HttpStatus.OK) @GetMapping(value = "/user/{name}") public void process(@PathVariable String name) { logger.info("User name: {}", name); } @ResponseStatus(value = HttpStatus.OK) @GetMapping(value = "/user/{name}/{email}") public void process2(@PathVariable String name, @PathVariable String email) { logger.info("User name: {} and email: {}", name, email); } @ResponseStatus(value = HttpStatus.OK) @GetMapping(value = "/book/{author}/{title}") public void process3(@PathVariable Map<String, String> vals) { logger.info("{}: {}", vals.get("author"), vals.get("title")); }}我们为 GET 请求提供了三个映射。
@ResponseStatus(value = HttpStatus.OK)@GetMapping(value = "/user/{name}")public void process(@PathVariable String name) { logger.info("User name: {}", name);}在此代码中,URI 模板变量绑定到name方法参数。
@ResponseStatus(value = HttpStatus.OK)@GetMapping(value = "/user/{name}/{email}")public void process2(@PathVariable String name, @PathVariable String email) { logger.info("User name: {} and email: {}", name, email);}通过指定多个@PathVariable注解,也可以绑定多个变量。
@ResponseStatus(value = HttpStatus.OK)@GetMapping(value = "/book/{author}/{title}")public void process3(@PathVariable Map<String, String> vals) { logger.info("{}: {}", vals.get("author"), vals.get("title"));}也可以使用Map<String, String>绑定多个变量。
$ mvn jetty:run
我们启动 Jetty 服务器。
$ curl localhost:8080/user/Peter/peter@gmail.com/
我们用curl发出请求。
22:04:35.273 INFO com.zetcode.controller.MyController - User name: Peter and email: peter@gmail.com
应用记录此消息。
在本教程中,我们使用 Spring 框架创建了一个 RESTful Web 应用。 我们已经演示了@PathVariable的用法。
