【问题标题】:Accept multiple params in a single PathVariable在单个 PathVariable 中接受多个参数
【发布时间】:2020-02-17 09:03:01
【问题描述】:
我有一个这样的控制器方法:
@PostMapping("/view/{location}")
public ModelAndView view(@PathVariable("location") String location) {
ModelAndView modelAndView = new ModelAndView();
return modelAndView;
}
这个方法可以接收类似的请求
"/view/a" 或 "/view/b" 使得 pathVariable location 变为 a 或 b。
但我希望同样的方法接收所有开头有 /view 的请求,以便 pathVariable "location" 保存其余数据。
例如
对于 /view/a/b/c 的请求,pathVariable location 将变为 a/b/c。 p>
类似于文件系统层次结构。
如果这样的事情在 Spring MVC 中是可能的,请告诉我,我对此很陌生。
【问题讨论】:
标签:
java
spring
spring-mvc
post
【解决方案1】:
看看这个article
这个想法是通过添加** 将所有以/view 开头的路径映射到单个控制器方法,但您必须使用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
【解决方案2】:
你可以按照之前分享的方法,
@GetMapping(value = "blog/**")
public Blog show(HttpServletRequest request){
String id = (String)
request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
System.out.println(id);
int blogId = Integer.parseInt(id);
return blogMockedData.getBlogById(blogId);
}
第二种方法是使用 RequestParam 而不是 Path 变量。
您将使用以下方法调用 api:
http://localhost:8080/blog?input=nabcd/2/nr/dje/jfir/dye
控制器看起来像:
@GetMapping(value = "blog")
public Blog show(@RequestParam("input") String input){
如果您确定输入中的斜线数量,您可以使用此处提到的任何方法help