@PathVariable 如何提取 URL 路径中的参数
使用 @pathvariable 注解可以直接将 url 路径片段绑定到控制器方法的参数上。只需在方法签名中定义参数并添加该注解,spring mvc 就会自动解析路径中的占位符并赋值给变量。如果路径参数名与参数变量名一致,可以省略注解中的值;若不一致,则必须显式指定路径中的占位符名称。这种方式适用于 restful 风格中通过路径标识资源 id 的场景。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@GetMapping("/users/{id}")
public String getUserById(@PathVariable Long id) {
return "User ID: " + id;
}
}当访问 /users/123 时,id 参数会被赋值为 123(类型为 Long),返回结果为 User ID: 123。如果路径中缺少占位符或类型转换失败,会抛出 HttpMessageNotReadableException 或 MethodArgumentTypeMismatchException。
路径参数缺失或格式错误时的默认处理机制
当请求路径不符合预期格式时,Spring Boot 默认会返回 HTTP 404 Not Found 或 400 Bad Request 状态码。如果路径参数是必需的且未提供,框架无法匹配映射,导致 404 错误。若提供了参数但类型不匹配(如期望整数却收到字符串),则会触发类型转换异常,通常表现为 400 错误。可以通过自定义全局异常处理器来统一捕获这些异常并返回更友好的 JSON 响应。

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleTypeMismatch(MethodArgumentTypeMismatchException ex) {
return "Invalid parameter type: " + ex.getName();
}
}上述代码定义了全局异常处理器,专门捕获 MethodArgumentTypeMismatchException。当用户访问 /users/abc 时,由于 id 参数期望为 Long 而实际传入 String,将触发此异常,返回 400 Bad Request 及自定义消息。对于路径完全匹配失败的情况(如访问 /user/123 而非 /users/123),Spring 不会进入控制器,而是由底层 DispatcherServlet 返回 404,此时需配置默认错误页面或使用 ErrorController 进行定制。
路径参数中包含特殊字符或空值时的具体行为
当路径参数包含斜杠、空格或其他保留字符时,URL 编码会影响参数的解析结果。例如,若路径为 /users/1%2Fadmin,解码后 id 的值为 1/admin。如果路径参数允许为空(如 /users/),Spring 默认会将空字符串转换为对应类型的零值或 null,具体取决于参数类型和配置。对于 String 类型,空路径段会被解析为空字符串 "";对于基本类型如 int,则可能引发转换异常。建议在路径设计时避免使用易混淆的分隔符,或在控制器中对空值进行显式校验。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class PathParamTestController {
@GetMapping("/items/{name}")
public String getItem(@PathVariable String name) {
if (name == null || name.isEmpty()) {
return "Name is empty or null";
}
return "Item: " + name;
}
}当访问 /items/ 时,name 参数为空字符串,返回 Name is empty or null。当访问 /items/my%20item 时,name 参数为 my item,返回 Item: my item。这种处理方式确保了即使路径中出现特殊字符或空值,程序也能安全响应,避免未处理的异常中断请求流程。


















