Spring @PathVariable 注解支持中文参数
在 Spring 框架中,@PathVariable 注解默认是支持中文的。当使用中文作为 PathVariable 的值时,可以直接在注解中使用中文字符串作为参数。
例如,假设有一个请求路径为 /users/{username},其中 username 是一个中文字符串,可以使用 @PathVariable 注解将其作为方法参数接收。
@GetMapping("/users/{username}")
public String getUser(@PathVariable String username) {
// 处理业务逻辑
return "User: " + username;
}
在上述代码中,username 参数就是从请求路径中获取的中文字符串。
需要注意的是,在实际开发中,为了避免中文乱码等问题,建议在配置文件中设置编码格式,并且使用 URL 编码方式进行请求。
# application.properties
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
另外,如果使用 @PathVariable 注解接收的中文字符串包含多个路径参数,需要使用 {} 将参数括起来,并使用正则表达式进行匹配。
@GetMapping("/users/{id}/{name}")
public String getUser(@PathVariable("id") int id, @PathVariable("name") String name) {
// 处理业务逻辑
return "User: " + id + ", " + name;
}
以上代码中,id 和 name 都是中文字符串,分别对应路径中的两个参数。
原文地址: https://www.cveoy.top/t/topic/pF5t 著作权归作者所有。请勿转载和采集!