0

我对 Spring@RequestMapping注释的行为感到困惑。在下面的代码中,test()被映射到"/test"并被test_test()映射到"/test/test/test". 这里发生了什么?如果我想映射test()到,我该怎么办"/test/test"

package com.mvc.spring;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/test")
public class Test {
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    String test() {
        return "test";
    }

    @RequestMapping(value = "/test/test", method = RequestMethod.GET)
    String test_test() {
        return "test";
    }
}
4

1 回答 1

1

Spring 是故意这样做的;当方法和类型级别的请求映射模式值匹配时,它只使用其中之一。@看org.springframework.util.AntPathMatcher#combine()

一种方法是在方法级别为 RequestMapping 值添加“/”后缀(如下所示),这样您就可以将"/test/test/"其用作 url(当然是 N ​​OT /test/test)。

@Controller
@RequestMapping(value = "/test")
public class Test {
    @RequestMapping(value = "/test/", method = RequestMethod.GET)
    String test() {
        return "test";
    }
}

不知道为什么没有记录。

所以,我认为匹配"/test/test"url 的唯一剩余方法是使用 URI 模板模式。

@Controller
@RequestMapping(value = "/test")
public class Test {
    @RequestMapping(value = "/{anythinghere}", method = RequestMethod.GET)
    String test() {
        return "test";
    }
}
于 2012-11-16T06:23:52.990 回答