Springboot 请求数据
请求方式
get
- 用RequestMapping
@RequestMapping("/hello") // 默认为get方式,或者可以写成@RequestMapping(value="/hello", method.RequestMethod.GET)
public String say() {return "hello";
}
- 用GetMapping
@GetMapping("/hello1")
public String say1() {return "hello";
}
- 有参方法
请求时在浏览器中输入: localhost:8080/hello?name=zhangsan&age=18
这个实体类里应有get set方法,要不返回为空
@RequestMapping("/hello2")
public String say2(Person person) {return person.toString();
}public class Person {private String name;private int age;public String getName() {return name;}public int getAge() {return age;}public void setName(String name) {this.name = name;}public void setAge(int age) {this.age = age;}public String toString() {return "name:" + name + ";age:" + age;}
}
请求时在浏览器中输入: localhost:8080/hello3/77?name=zhangsan&age=18
@RequestMapping("/hello3/{id}")
public String say3(@PathVariable(value="id") Integer id,@RequestParam(value="name") String name,@RequestParam(value="age", required=false, defaultValue="1000") String age){return "id: " + id + ", name: " + name + ", age: " + age;
}
post
- 用RequestMapping
@RequestMapping("/hello4", method=RequestMethod.POST)
public String say4() {return "hello 4";
}
- 用PostMapping
@PostMapping("/hello5")
public String say5() {return "hello 5";
}
- 有参方法,模拟post请求需要下载postman等插件进行模拟
与get区别在于应在实体类上加@RequestBody注解,原因未知
@PostMapping("/hello6")
public String say6(@RequestBody Person person) {System.out.println(person.toString());return person.toString();
}
post发送请求用x-www-form-urlencoded格式可以传递参数,用form-data只会有默认值,具体区别请参考 https://blog.csdn.net/u013827143/article/details/86222486
@PostMapping("/hello7")
public String say7(@RequestParam(value="name") String name,@RequestParam(value="age") String age) {String result = "name: " + name + ", age:" + age;System.out.println(result);return result;
}
http请求格式
| 请求部分 | 请求内容 |
|---|---|
| 状态行(请求方法+请求协议) | GET /test.html HTTP/1.1 |
| 请求头 | Accept: image/gif |
| 请求体 |
| POST提交数据方式 | 区别 |
|---|---|
| application/x-www-form-urlencoded | |
| multipart/form-data | |
| application/json | |
| text/xml |
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
