gpt4 book ai didi

java - 在单个 PathVariable 中接受多个参数

转载 作者:行者123 更新时间:2023-11-29 04:06:17 25 4
gpt4 key购买 nike

我有一个这样的 Controller 方法:

@PostMapping("/view/{location}")
public ModelAndView view(@PathVariable("location") String location) {

ModelAndView modelAndView = new ModelAndView();
return modelAndView;
}

此方法能够接收类似

的请求

"/view/a" or "/view/b" such that pathVariable location becomes a or b.

但我希望同样的方法接收所有以/view 开头的请求,这样 pathVariable "location" 就可以保存其余数据。

例如

for a request as /view/a/b/c, the pathVariable location will become a/b/c.

就像一个文件系统层次结构。

请让我知道在 Spring MVC 中是否可以做这样的事情,我对此很陌生。

最佳答案

看看这个 article

想法是通过添加 ** 将所有以 /view 开头的路径映射到单个 Controller 方法,但您必须使用 HttpServletRequest 而不是 @PathVariable

因此,在您的情况下,它将是这样的:

@PostMapping("/view/**")
public ModelAndView view(HttpServletRequest request) {
String pathVariable = extractId(request);

ModelAndView modelAndView = new ModelAndView();
return modelAndView;
}

private String extractId(HttpServletRequest request) {
String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
return new AntPathMatcher().extractPathWithinPattern(bestMatchPattern, path);
}

另外,看看这个 question

关于java - 在单个 PathVariable 中接受多个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58483485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com