Daniel Gruszczyk
Daniel Gruszczyk

Reputation: 5622

Spring request mapping catching part of uri to PathVariable

I need something similar to enter link description here
So my path would be: /something/else/and/some/more I would like to map it like so:

@RequestMapping(value="/something/**", method=RequestMethod.GET)
public String handleRequest(String theRestOfPath){ /***/ }

Or

@RequestMapping(value="/something/**", method=RequestMethod.GET)
public String handleRequest(String[] theRestOfPathArr){ /***/ }

The thing is ... I would like everything matched by ** to be passed to the method either:
1. as a string (theRestOfPath = "/else/and/some/more"),
2. or as an array (theRestOfPathArr = ["else","and","some","more"]).

The number of path variables can vary, so I can't do:

@RequestMapping(value="/something/{a}/{b}/{c}", method=RequestMethod.GET)
public String handleRequest(String a, String b, String c){ /***/ }

Is there a way to do that?
Thanks :)

---EDIT---
The solution I ended up with:

@RequestMapping(value = "/something/**", method = RequestMethod.GET)
@ResponseBody
public TextStory getSomething(HttpServletRequest request) {
    final String URI_PATTERN = "^.*/something(/.+?)(\\.json|\\.xml)?$";
    String uri = request.getRequestURI().replaceAll(URI_PATTERN, "$1");
    return doSomethingWithStuff(uri);
}

Upvotes: 1

Views: 2542

Answers (2)

Prakash Bhagat
Prakash Bhagat

Reputation: 1446

There's feature in spring MVC which will do parsing for you. Just use @PathVariable annotation.

Refer: Spring mvc @PathVariable

Upvotes: 0

Steve
Steve

Reputation: 9490

If you include an HttpServletRequest as an argument to your method, then you can access the path being used. i.e.:

@RequestMapping(value="/something/**", method=RequestMethod.GET)
public String handleRequest(HttpServletRequest request){
    String pattern = (String) request.getAttribute(
                     HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
    String path = new AntPathMatcher()
            .extractPathWithinPattern(pattern, request.getServletPath());

    path = path.replaceAll("%2F", "/");
    path = path.replaceAll("%2f", "/");

    StringTokenizer st = new StringTokenizer(path, "/");
    while (st.hasMoreElements()) {
        String token = st.nextToken();
        // ...
    }
}

Upvotes: 2

Related Questions