Ambiguous URLs, one with PathVariable

后端 未结 2 1576
北荒
北荒 2021-01-16 19:21

I have Spring 3.2 web app and i have controller with following request mappings:

@RequestMapping(value = \"/test/{param1}\", method = RequestMethod.GET)
publ         


        
相关标签:
2条回答
  • 2021-01-16 19:52

    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.

    0 讨论(0)
  • 2021-01-16 19:52

    I'm afraid it is not the expected answer, but as it is not specified in the documentation it should be regarded as undefined.

    You could just try (eventually with putting "/test/logging" method first if source file), but even if it worked, you could not be sure that it will still work with another version of Spring Framework.

    My advice is: if you can, avoid such ambiguous URLs, if you cannot, just have a single catchall @RequestMapping and forward from it by hand:

    @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(//..
    

    That way, you have full control on what method processes what url. Not necessarily the nicest way, but it is at least robust ...

    0 讨论(0)
提交回复
热议问题