Spring Boot 获取 URL 中 PathVariable 的值
Spring Boot About 971 words@PathVariable
@GetMapping("/api/post/{postId}")
public Post getPost(@PathVariable Integer postId) {
return postMgmtService.findById(postId);
}
其他方法
Map
的Key
就是{key}
大括号中的值。
View.PATH_VARIABLES
和HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE
区别是:如果URL
中没有PathVariable
的话前者会返回null
,后者返回空集合;并且前者返回的是HashMap
,后者返回的是Collections.UnmodifiableMap
。
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.HandlerMapping;
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
Map<String, Object> map = (Map<String, Object>) attributes.getAttribute(View.PATH_VARIABLES, RequestAttributes.SCOPE_REQUEST);
Map<String, Object> map2 = (Map<String, Object>) attributes.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE, RequestAttributes.SCOPE_REQUEST);
Views: 645 · Posted: 2024-04-01
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...