EchoDemo's Blogs

SpringBoot中Controller的使用

1、Controller方法和类的注解

"1"

其中@RequestMapping可以给整个Controller类设置注解。还可以通过如下的设置让不同的链接参数来进行访问:

@RequestMapping(value = {"hello", "hi"}, method = RequestMethod.GET)
public String say(){
    return "Hello SpringBoot!";
}

"2"
"3"

当然为了让代码更加得简洁,可以使用@GetMapping(value = “/hello”)和@PostMapping(value = “/hello”)来替代@RequestMapping(value = “/hello”, method = RequestMethod.GET)和@RequestMapping(value = “/hello”, method = RequestMethod.POST)的。

2、Controller当中的参数传递

"4"

(1)@PathVariable

@RequestMapping(value = "/hello/{id}",method = RequestMethod.GET)
public String say(@PathVariable("id") Integer id){
    return "id: " + id;
}

"5"

(2)@RequestParam(可以设置默认值)

@RequestMapping(value = "/hello",method = RequestMethod.GET)
public String say(@RequestParam(value = "id", required = false, defaultValue = "0") Integer id){
    return "id: " + id;
}

"6"
"7"

🐶 您的支持将鼓励我继续创作 🐶
-------------本文结束感谢您的阅读-------------