只获取@Requestmapping的通配符部分

时间:2014-08-19 11:47:43

标签: 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


        // ...
    }

}|

2 个答案:

答案 0 :(得分:15)

似乎这个问题已经在这里得到解决:Spring 3 RequestMapping: Get path value虽然接受的答案回答了这个问题。一个建议的解决方案,this one,似乎有效,因为我刚尝试过:

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

}

即使在达到接受答案的分数之前还有很长的路要走,我建议对未被接受的答案进行提升。我不会感到惊讶的是,在这个其他主题和现在接受答案的时间之间,规格已经发生变化(因为错误的答案无法达到如此高的分数)。

答案 1 :(得分:6)

使用像这样的@PathVariable注释

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

}