传送门:springboot开发学习准备
通过上一篇的准备,我们完成了一个最基本的springboot web项目搭建,这次主要是了解springboot常用的http接口开发方式
一. 安装postman
为了测试各种请求方式,这里使用谷歌插件 postman,这个工具的作用就是实现各种请求发送方式.如果你有其它测试工具可以跳过
官网下载: https://www.getpostman.com, 点击 download app,选择对应的版本下载
二. 常用http请求接收方式
1.restful风格get请求
@GetMapping(path = "test1/{user_name}/{password}")
Object test1(@PathVariable("user_name") String userName, @PathVariable String password){
Map map = new HashMap();
map.put("userName",userName);
map.put("password",password);
return map;
}
- @GetMapping是@RequestMapping子类,这里相当于 @RequestMapping(path = “/{user_name}/{password}”,method = RequestMethod.GET)
相对的还有 @PostMapping @PutMapping 和#DeleteMapping - @PathVariable 接收参数标签,可以设置value别名,不写value值默认按参数名接收
- 可以在{}前面添加固定值防止数据泄露如 @GetMapping(path = “test1/aaa{user_name}/bbb{password}”)
- 启动项目,验证 http://localhost:8080/test1/chen/123
2. 参数在请求行
数在请求行后以 ?key1=value1&key2=value2 形式提交
@RequestMapping("test2")
Object test2(@RequestParam(defaultValue = "name") String userName,@RequestParam(required = true) String password,String age){
Map map = new HashMap();
map.put("userName",userName);
map.put("password",password);
map.put("age",age);
return map;
}
- @RequestMapping表示请求方式无限制(可以是get或post或其它)
- @RequestParam 对参数进行设置,不写默认映射参数名 属性:name和value 都是配置映射名, defaulValue 参数为空或不传时的默认值, required=true 表示参数必填
- 验证:http://localhost:8080/test2?userName=&password=456&age=27
3. 使用封装类接收
@RequestMapping("test3")
Object test3(@RequestBody User user){
return user;
}
- user类成员变量必须与参数一致,并提供set/get方法
- 使用 @RequestBody 自动封装对象
- 请求方式必须使用head格式Content-Type: application/json
4.使用HttpServletRequest获取请求参数
@RequestMapping("test5")
Object test5(HttpServletRequest request){
Map map = new HashMap();
String userName = request.getParameter("userName");
String password = request.getParameter("password");
map.put("userName",userName);
map.put("password",password);
return map;
}
- 参数接收使用HttpServletRequest
- 使用 request.getParameter(“key”)获取参数
- 测试: http://localhost:8080/test5?userName=chen&password=456
5. 获取http头信息head
@RequestMapping("test4")
Object test4(@RequestHeader("Content-Type") String headMessage,@RequestHeader("token") String token,String id){
Map map = new HashMap();
map.put("headMessage",headMessage);
map.put("token",token);
map.put("id",id);
return map;
}
总结:如果项目使用restful风格,则使用方式1,常用的接口开发模式是方式2和方式4,相对的更加灵活方便