从零开始的SpringMVC生活(六)

本文介绍了REST风格开发,包括如何通过HTTP方法区分操作,如GET、POST、PUT、DELETE等。讨论了如何使用@PathVariable、@RequestParam和@RequestBody处理不同类型的参数,以及如何通过简化Controller和RequestMapping注解来优化代码结构。

REST开发

表现形式状态转换

优点:隐藏资源的访问行为,书写简化

REST风格通过使用行为动作区分操作

  • localhost/users           GET(查询)                 查询全部信息
  • localhost/users/1        GET(查询)                 查询指定信息
  • localhost/users/          POST(新增/保存)      添加用户信息    
  • localhost/users/          PUT(修改、更新)      修改用户信息  
  • localhost/users/1        DELETE(删除)          删除用户信息      

使用这种方式访问称为RESTful

项目结构

config中文件内容没变

    @RequestMapping(value = "/users",method = RequestMethod.POST)
    @ResponseBody
    public String save(){
        return "user save run";
    }

通过post请求访问users,效果如下:

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

@PathVariable注解表示参数从地址中获取,value中的变量名与形参命应一致

效果如图:

@RequestMapping(value = "/users",method =RequestMethod.PUT)
@ResponseBody
public String update(@RequestBody User user){
    return "user update run "+user;
}

    @RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
    @ResponseBody
    public String getById(@PathVariable Integer id){
        return "user getById " + id + " run";
    }

    @RequestMapping(value = "/users",method = RequestMethod.GET)
    @ResponseBody
    public String getAll(){
        return "user getAll run";
    }

参数注解区别
@RequestParam用于接受url地址传参或表单传参

@RequestBody用于接受json数据

@PathVariable用于接收路径参数‘

应用

发送请求参数超过一个时,以json为主,@RequestBody应用较广

发送非json格式数据,选用@RequestParam请求参数

采用RESTful进行开发,当参数是数量较少时,可以采用@PathVariable接收,用于传递id值

REST风格的简化开发

首先每一个Controller中,value的值基本一致,且每一个方法都使用了@ResponseBody注解,并且@Controller与@ResponseBody可以简写为@RestController,所以可以简化为:

@RestController
@RequestMapping("/users")
public class UserController {}

method的值也可以转换为注解,带有value的,将value也放入注解中。

    @PostMapping
    public String save(){
        return "user save run";
    }
    
    @DeleteMapping("/{id}")
    public String delete(@PathVariable Integer id){
        return "user delete " + id + " run";
    }

    @PutMapping
    public String update(@RequestBody User user){
        return "user update run "+user;
    }

    @GetMapping("/{id}")
    public String getById(@PathVariable Integer id){
        return "user getById " + id + " run";
    }

    @GetMapping
    public String getAll(){
        return "user getAll run";
    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值