SpringBoot 第三天——@RestController、@RequestMapping、@PathVariable、@RequestPaeam、@GetMapping的使用
程序员文章站
2022-03-16 14:15:57
...
s廖师兄,2小时学会Spring Boot 点击打开链接
番外篇:postman软件可以用来模拟发送post和get请求
一、@Controller 和@RestController 两个注解的异同点在第一天的遇到的坑中记录过,这里就不再记录了。
二、@RequestMapping(value = {"hello", "hi"}, method = RequestMethod.GET)
如果希望/hello 和 /hi 能匹配同一个方法
@RequestMapping(value = {"hello", "hi"}, method = RequestMethod.GET)
public String sayHello() {
System.out.println("Hello SpringBoot");
//return "Hello:" + cupSize + ":" + age;
//return content;
return girl.getCupSize();
}
三、@PathVariable
优点:这种写法,url 会很简洁
第一种:参数在最后面
@RequestMapping(value = "/hello/{id}", method = RequestMethod.GET)
public String sayHello(@PathVariable("id") Integer myId) {
System.out.println("Hello SpringBoot");
//return "Hello:" + cupSize + ":" + age;
//return content;
//return girl.getCupSize();
return "id:" + myId ;
}
第二种:参数在前面
@RequestMapping(value = "/{id}/hello", method = RequestMethod.GET)
public String sayHello(@PathVariable("id") Integer myId) {
System.out.println("Hello SpringBoot");
//return "Hello:" + cupSize + ":" + age;
//return content;
//return girl.getCupSize();
return "id:" + myId ;
}
四、@RequestParam
需要注意的是:@RequestParam("id)中的参数 id 要和 url 中一模一样
1、第一种用法
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello(@RequestParam("id") Integer myId) {
return "id:" + myId ;
}
2、第二种用法:如果不传就给默认值
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String sayHello(@RequestParam(value = "id", required = false, defaultValue = "99") Integer myId) {
return "id:" + myId ;
}
五、@GetMapping
优点:简化代码。如果是GET请求就用 @GetMapping ,如果是POST请求就用 @PostMapping
//@RequestMapping(value = "/hello", method = RequestMethod.GET)
@GetMapping("/hello")
public String sayHello(@RequestParam(value = "id", required = false, defaultValue = "99") Integer myId) {
return "id:" + myId ;
}
下一篇: 萌新react第一步:基础使用