首页 > 解决方案 > Find which url was used to access the controller when multiple url mapping to the same controller method

问题描述

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

标签: javaspringspring-mvcmodel-view-controller

解决方案


您可以使用HttpServletRequest#getServletPath哪个:

返回此请求的 URL 中调用 servlet 的部分。此路径以“/”字符开头,包括 servlet 名称或 servlet 路径,但不包括任何额外的路径信息或查询字符串。

如下:

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

推荐阅读