Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only wildcard part of @Requestmapping

Tags:

spring-mvc

I'm using wildcard mapping on controller action, and want to get string matched by wildcard. How can I do it the correct way? Without using substring etc.

@Controller
@RequestMapping(value = "/properties")
public class PropertiesController {

    @RequestMapping(value = "/**", method=RequestMethod.GET)
    public void getFoo() {

        String key = (String) request. getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        // returns "/properties/foo/bar" ... 
        // I want only "foo/bar" part


        // ...
    }

}|
like image 282
David Avatar asked Aug 19 '14 11:08

David


2 Answers

It seems that the question have already been addressed here : Spring 3 RequestMapping: Get path value although the accepted answer does not answer the question. One suggested solution, this one, seems to work since I just tried it :

@Controller
@RequestMapping(value = "/properties")
public class PropertiesController {

    @RequestMapping(value = "/**", method=RequestMethod.GET)
    public void getFoo(final HttpServletRequest request) {

        String path = (String) request.getAttribute(
            HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
        String bestMatchPattern = (String ) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);

        AntPathMatcher apm = new AntPathMatcher();
        String finalPath = apm.extractPathWithinPattern(bestMatchPattern, path);
        // on "/properties/foo/bar", finalPath contains "foo/bar"
    }

}

I would advise upvoting the non-accepted answer even if there is a long way to go before it reaches the score of the accepted answer. I wouldn't be surprised to learn that the specs have changed between the time the answer was accepted on this other thread and now (since there is no way a wrong answer could have reached such a high score).

like image 179
m4rtin Avatar answered Sep 30 '22 08:09

m4rtin


Use the @PathVariable annotation like this

@RequestMapping(value = "/{key}")
public void getFoo(@PathVariable("key") int key) {

}
like image 36
Tim Coy Avatar answered Sep 30 '22 07:09

Tim Coy