REST风格 - RESTful入门案例

1.设定http请求动作

常用 GET POST PUT DELETE 对应增删改查

s

 @RequestMapping(value = "/users", method = RequestMethod.POST)
    @ResponseBody
    public String save() {
        System.out.println("user save ...");
        return "{'module':'user save测试'}";
    }

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    @ResponseBody
    public String getById() {
        System.out.println("user get ...");
        return "{'module':'user get测试'}";
    }

    @RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public String delete(@PathVariable Integer id) {
        System.out.println("user delete ..." + id);

        return "{'module':'user delete'}" + id;
    }

 2.设定请求参数(路径变量)

@RequestMapping(value = "/users/{id}", method = RequestMethod.DELETE)

方法中 @PathVariable Integer id  接收 路径变量 参数


名称:@RequestMapping

类型:方法注解

位置: SpringMVC控制器方法定义上方

作用:设置当前控制器方法请求访问路径

示例:

 @RequestMapping(value = "/users", method = RequestMethod.POST)
    @ResponseBody
    public String save() {
        System.out.println("user save ...");
        return "{'module':'user save测试'}";
    }

 属性:value(默认):请求访问路径

method: http请求动作(GET/POST/PUT/DELETE)


接收参数:

@RequestParam用于接收url地址传参或表单传参

@RequestBody用于接收json数据

@PathVariable 用于接收路径参数,使用{参数名称}描述路径参数

应用:

  • 后期开发中,发送请求参数超过1个时,以json格式为主,@RequestBody应用较多
  • 如果发送非json格式数据,选择@RequestParam接收请求参数
  • 采用RESTful进行开发,当参数数量较少时,例如1个,可采用@PathVariable接收请求路径变量,通常用于传Id值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值