前言
对于Spring Boot的controller,相必大家已经很熟悉了,@RequestMapping可以加在类上面,也可以加在方法上面,但是对于一些比较特殊的场景,你有想过该这个注解是如何工作的吗?
示例
我举个例子,下面这段代码,我应该通过哪个url才能调用到hello1方法呢?
@RestController
@RequestMapping
public class TestController {
@RequestMapping
public String hello1() {
return "hello1";
}
}
难不成直接访问根路径 / 就可以了?
你没有猜错,我们来尝试一下:
$ curl localhost:8080/
hello1%
我稍微修改一下代码:
@RestController
@RequestMapping("a")
public class TestController {
@RequestMapping
public String hello1() {
return "hello1";
}
}
这时直接访问 localhost:8080/a 或者是 localhost:8080/a/ 都可以得到想要的结果。
我再修改代码如下所示:
@RestController
@RequestMapping("a")
public class TestController {
@RequestMapping("/")
public String hello1() {
return "hello1";
}
}
这时候 /a 路径会返回404的错误,而 /a/ 会返回hello1。原来 斜杠与不加斜杠是两个不同的路径。
但是对于根路径来说,加与不加斜杠表示相同的意思,不会像上面那样产生区别。
总结
- 对于方法上的@RequestMapping来说,开头加与不加斜杠是相同的。
- 在类上有@RequestMapping的时候,如果类上有值,那么方法上结尾有没有斜杠是有区别的
文章评论