1

I have a controller method as this:

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

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

This method is capable of receiving requests like

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

But I want this same method to receive all the requests having /view in their beginning, such that the pathVariable "location" holds the rest of the data.

for example

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

like a file system hierarchy.

Please let me know if such a thing is possible in Spring MVC, and I am very new at this.

V.Aggarwal
  • 557
  • 4
  • 12

2 Answers2

2

Check out this article

The idea is to map all the paths which start with /view to a single controller method by adding **, but you'll have to use HttpServletRequest instead of @PathVariable.

So, in your case, it'll be something like this:

@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);
}

Also, check out this question

htshame
  • 6,599
  • 5
  • 36
  • 56
1

You could go by the approach shared earlier,

@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);
}

Second way is to use RequestParam instead of Path variable.

you will call the api using :

http://localhost:8080/blog?input=nabcd/2/nr/dje/jfir/dye

controller will look like : @GetMapping(value = "blog") public Blog show(@RequestParam("input") String input){


If you are certain about the number of slash in your input, you could go with any approach mentioned here help

javaGroup456
  • 313
  • 1
  • 6
  • 21