Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional path variables in Spring-MVC RequestMapping URITemplate

I have the following mapping:

@RequestMapping(value = "/{first}/**/{last}", method = RequestMethod.GET)
public String test(@PathVariable("first") String first,  @PathVariable("last")  
  String last) {}

Which for the following URIs:

foo/a/b/c/d/e/f/g/h/bar
foo/a/bar
foo/bar

maps foo to first and bar to last and works fine.

What I would like is something that maps everything between foo and bar into a single path param, or null if there is no middle (as in the last URI example):

@RequestMapping(value = "/{first}/{middle:[some regex here?]}/{last}", 
  method = RequestMethod.GET)
public String test(@PathVariable("first") String first, @PathVariable("middle")
  String middle, @PathVariable("last") String last) {}

Pretty stuck on the regex since I was hoping that something simple like {middle:.*}, which only maps to /foo/a/bar, or {middle:(.*/)*}, which seems to map to nothing.

Does the AntPathStringMatcher tokenize upon "/" prior to applying regex patterns? (making patterns that cross a / impossible) or is there a solution?

FYI this is in Spring 3.1M2

This seem similar to @RequestMapping controllers and dynamic URLs but I didn't see a solution there.

like image 900
laochan Avatar asked Oct 20 '11 20:10

laochan


1 Answers

In my project, I use inner variable in the springframework:

@RequestMapping(value = { "/trip/", // /trip/
        "/trip/{tab:doa|poa}/",// /trip/doa/,/trip/poa/
        "/trip/page{page:\\d+}/",// /trip/page1/
        "/trip/{tab:doa|poa}/page{page:\\d+}/",// /trip/doa/page1/,/trip/poa/page1/
        "/trip/{tab:trip|doa|poa}-place-{location}/",// /trip/trip-place-beijing/,/trip/doa-place-shanghai/,/trip/poa-place-newyork/,
        "/trip/{tab:trip|doa|poa}-place-{location}/page{page:\\d+}/"// /trip/trip-place-beijing/page1/
}, method = RequestMethod.GET)
public String tripPark(Model model, HttpServletRequest request) throws Exception {
    int page = 1;
    String location = "";
    String tab = "trip";
    //
    Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
    if (pathVariables != null) {
        if (pathVariables.containsKey("page")) {
            page = NumberUtils.toInt("" + pathVariables.get("page"), page);
        }
        if (pathVariables.containsKey("tab")) {
            tab = "" + pathVariables.get("tab");
        }
        if (pathVariables.containsKey("location")) {
            location = "" + pathVariables.get("location");
        }
    }
    page = Math.max(1, Math.min(50, page));
    final int pagesize = "poa".equals(tab) ? 40 : 30;
    return _processTripPark(location, tab, pagesize, page, model, request);
}

See HandlerMapping.html#URI_TEMPLATE_VARIABLES_ATTRIBUTE

like image 169
imxylz Avatar answered Sep 19 '22 13:09

imxylz