Abhi Abhi - 7 months ago 22
Java Question

Spring MVC map controller with trailing string of url

Is it possible to map a spring mvc controller by trailing keyword of a url. e.g, lets suppose I have following urls:


  1. example.com/{cityName}

  2. example.com/{cityName}/{categoryName}

  3. example.com/{cityName}/ping

  4. example.com/{cityName}/{categoryName}/ping



I want to have 3 controller methods. 1st url should be handled by controller "X", 2nd url should be handled by method "Y" and 3rd, 4th url should be handled by single method "Z". This means that any url ending by
/ping
should be handled by method "Z" only. No matter what is leading content of that url.

Is this feasible in Spring MVC?

Answer

Is it possible to map a spring mvc controller by trailing keyword of a url?

Yes, you can use Ant-style path patterns. Following controller will handle any request to URLs ending with /ping, with arbitrary number of levels:

@RequestMapping(path = "**/ping")
public String Z(HttpServletRequest request) {
    return request.getRequestURI();
}

In order to extract those Path Variables, e.g. cityName and categoryName, you should inject the HttpServletRequest to the method handler.

In addition to URI templates, the @RequestMapping annotation also supports Ant-style path patterns. You can read more on Spring Documentation.