Spring Boot 获取 URL 中 PathVariable 的值

Spring Boot About 971 words

@PathVariable

@GetMapping("/api/post/{postId}")
public Post getPost(@PathVariable Integer postId) {
    return postMgmtService.findById(postId);
}

其他方法

MapKey就是{key}大括号中的值。

View.PATH_VARIABLESHandlerMapping.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: 581 · Posted: 2024-04-01

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh