只获取@Requestmapping的通配符部分

Dav*_*vid 5 spring-mvc

我在控制器操作上使用通配符映射,并希望通过通配符获得字符串匹配.我怎么能以正确的方式做到这一点?不使用子串等

@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


        // ...
    }

}|
Run Code Online (Sandbox Code Playgroud)

m4r*_*tin 15

看来这个问题已经在这里得到解决:Spring 3 RequestMapping:获取路径值,尽管接受的答案没有回答问题.一个建议的解决方案,这个,似乎工作,因为我刚试过它:

@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"
    }

}
Run Code Online (Sandbox Code Playgroud)

即使在达到接受答案的分数之前还有很长的路要走的时候,我建议对未被接受的答案进行推荐.我不会感到惊讶的是,在另一个线程上接受答案的时间与现在之间的规格已经发生了变化(因为错误的答案无法达到如此高的分数).


小智 6

像这样使用@PathVariable注释

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

}
Run Code Online (Sandbox Code Playgroud)