4

I see Spring MVC multiple url mapping to the same controller method

So now I have a method defined as

@RequestMapping(value = {"/aaa", "/bbb", "/ccc/xxx"}, method = RequestMethod.POST)
public String foo() {
    // was it called from /aaa or /bbb
}

At run time, I want to know if the controller was called from /aaa or /bbb

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
Raj
  • 747
  • 1
  • 9
  • 19
  • You could use HttpServletRequest::getRequestURL then strip it and parse the uri. – dbl Sep 10 '18 at 17:59
  • Instead of passing HttpServletRequest object as argument for each controller method you can use [HandlerInterceptor](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html). Take a look at this [guide](https://www.baeldung.com/spring-mvc-handlerinterceptor) – Kamil W Sep 10 '18 at 18:37

1 Answers1

2

You can use HttpServletRequest#getServletPath which:

Returns the part of this request's URL that calls the servlet. This path starts with a "/" character and includes either the servlet name or a path to the servlet, but does not include any extra path information or a query string.

As follow:

@RequestMapping(value = {"/aaa", "/bbb", "/ccc/xxx"}, method = RequestMethod.POST)
public String foo(HttpServletRequest request) {
  String path = request.getServletPath(); // -> gives "/aaa", "/bbb" or "/ccc/xxx"
}
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80