不明确的URL,一个带有PathVariable

时间:2015-07-31 12:26:57

标签: spring spring-mvc

我有Spring 3.2网络应用程序,我有控制器以及以下请求映射:

@RequestMapping(value = "/test/{param1}", method = RequestMethod.GET)
public String method1(@PathVariable(value = "param1") String param1, ..

@RequestMapping(value = "/test/login", method = RequestMethod.GET)
public String method2(//..

如果有人要求提供url / test / login,我可以确定是否会调用method2?是否有任何因素根据春天决定如何处理它?它是否始终选择没有PathVariable的URL(如果存在)?我在Spring doc中找不到任何东西。

2 个答案:

答案 0 :(得分:3)

Can i be sure that if someone ask for url /test/login the method2 will be invoked? Yes.

The mappings are resolved by specificity, the relevant piece of doc is available here

A pattern with a lower count of URI variables and wild cards is considered more specific. For example /hotels/{hotel}/* has 1 URI variable and 1 wild card and is considered more specific than /hotels/{hotel}/** which as 1 URI variable and 2 wild cards.

If two patterns have the same count, the one that is longer is considered more specific. For example /foo/bar* is longer and considered more specific than /foo/*.

When two patterns have the same count and length, the pattern with fewer wild cards is considered more specific. For example /hotels/{hotel} is more specific than /hotels/*.

If the two mappings match a request, a more specific will apply. Out of the two mappings, /test/login is more specific.

答案 1 :(得分:0)

我担心这不是预期的答案,但由于未在文档中指明,因此应将其视为 undefined

你可以尝试(最后如果源文件首先使用“/ test / logging”方法),但即使它有效,你也不能确定它是否仍然适用于另一个版本的Spring Framework。

我的建议是:如果可以的话,请避免使用这些含糊不清的网址,如果不能,只需拥有一个@RequestMapping并从中转发手动

@RequestMapping(value = "/test/{param1}", method = RequestMethod.GET)
public String method0(@PathVariable(value = "param1") String param1, ...
    ) { // union of all parameters for both method1 and method2
    String ret;
    if ("login".equals(param1)) {
        ret = method2(/* pass parameters for method 2 */ ...);
    }
    else {
        ret = method1(/* params for method1 */ param1, ...);
    }
    return ret;
}

public String method1(String param1, ..

public String method2(//..

这样,您可以完全控制哪个方法处理哪个url。不一定是最好的方式,但它至少是健壮的......