springboot学习二:常用http请求

传送门: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;
}
  1. @GetMapping是@RequestMapping子类,这里相当于 @RequestMapping(path = “/{user_name}/{password}”,method = RequestMethod.GET)
    相对的还有 @PostMapping @PutMapping 和#DeleteMapping
  2. @PathVariable 接收参数标签,可以设置value别名,不写value值默认按参数名接收
  3. 可以在{}前面添加固定值防止数据泄露如 @GetMapping(path = “test1/aaa{user_name}/bbb{password}”)
  4. 启动项目,验证 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;

}
  1. @RequestMapping表示请求方式无限制(可以是get或post或其它)
  2. @RequestParam 对参数进行设置,不写默认映射参数名 属性:name和value 都是配置映射名, defaulValue 参数为空或不传时的默认值, required=true 表示参数必填
  3. 验证:http://localhost:8080/test2?userName=&password=456&age=27

3. 使用封装类接收

@RequestMapping("test3")
Object test3(@RequestBody User user){
    return user;
}
  1. user类成员变量必须与参数一致,并提供set/get方法
  2. 使用 @RequestBody 自动封装对象
  3. 请求方式必须使用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;
}
  1. 参数接收使用HttpServletRequest
  2. 使用 request.getParameter(“key”)获取参数
  3. 测试: 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,相对的更加灵活方便

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值