Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you match a URL part in Spring MVC?

Is there a way to math the remaining URL part in a Spring controller?

i.e. if my route is /user/{userId}/* can I get the userId param and the rest of the url? The * part?

For example for /user/1/this/is/a/path.html?a=b I should get userId = 1 and userUrl = /this/is/a/path.html?a=b

I've seen some solutions and did some Googling but they seem kind of strange way to do it (most likely due to the answers being for an older version of Spring) So in a more recent version how can this e done in a clean way?

like image 720
daniels Avatar asked Nov 21 '25 08:11

daniels


1 Answers

Yes, here is an example adapted from this answer

@GetMapping("/user/{userId}/**")
    public void get(@PathVariable("userId") String userId, HttpServletRequest request){
        String path = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String  patternMatch = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        AntPathMatcher apm = new AntPathMatcher();
        String finalPath = apm.extractPathWithinPattern(patternMatch, path);
    }

In this example userId = 1 and finalPath = this/is/a/path.html

like image 153
Kyle Anderson Avatar answered Nov 23 '25 16:11

Kyle Anderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!