• REST风格(黑马笔记)


    简介

    REST(Representational State Transfer),表现形式状态转换。

    • 传统风格资源描述形式

    http://localhost/user/getById?id=1
    http://localhost/user/saveUser

    • REST风格描述形式

    http://localhost/user/1
    http://localhost/user

    优点:

    • 隐藏资源的访问行为,无法通过地址得知对方是何种操作
    • 书写简化

    按照REST风格访问资源时使用行为动作区分对资源进行了何种操作,如:

    • http://localhost/users // 查询全部用户信息 GET(查询)
    • http://localhost/users/1 // 查询指定用户信息 GET(查询)
    • http://localhost/users // 添加用户信息 POST(新增/保存)
    • http://localhost/users // 修改用户信息 PUT(修改/更新)
    • http://localhost/users/1 // 删除用户信息 DELETE(删除)
      提供REST风格对资源进行访问成为RESTFUL。

    REST风格实现

    1. 将相关的所有方法前缀设置为USERS
    2. 使用method 参数将对应的方法行为进行设定。
      例如无参的方法:
    @RequestMapping(value = "/users", method = RequestMehtod.POST)
    @RequestBody
    public String save() {
    	System.out.println("user save");
    	return "{'module' : 'save success!'}";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    对于有参数的时候:

    @RequestMapping(value = "/users/{id}", method = RequestMehtod.DELETE)
    @RequestBody
    public String delete(@PathVariable Integer id) {
    	System.out.println("user : " + id +  " delete");
    	return "{'module' : 'delete id success!'}";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    1. 使用@PathVariable注解
    2. 在mapping路径后添加/{id} ,保证id名称跟形参一致

    在这里插入图片描述

    RESTful快速开发

    1. 简化前面的路径名

    @RequestMapping(value = "/users/{id}", method = RequestMehtod.DELETE)中的路径放到类上
    @RequestMapping(value = "/users/{id}"}

    1. 简化方法前面的@RequestBody注解
    1. 在类上添加@RequestBody
    2. @Controller@RequestBody 合并,使用@RestController
    1. 将方法参数上指定的方法使用注解来优化:

    修改前: @RequestMapping(value = "/users/{id}", method = RequestMehtod.DELETE)

    修改后:@DeleteMapping("{/id}")

  • 相关阅读:
    到底什么是LPO?
    jQuery
    c++ 广度优先搜索(Breadth-First Search,BFS)
    HMS Core热门Kit Top问题合集,你要问的,这里全都有!
    linux技巧:vim分屏显示文件
    (Java高级教程)第一章Java多线程基础-第一节1:多线程概念和Java中创建线程的方式
    python虚拟环境的理解
    中国日用化工市场竞争格局展望及未来战略分析报告2022年版
    png转gif怎么操作?png动图怎么制作
    算法通关村 | 透彻理解动态规划
  • 原文地址:https://blog.csdn.net/Nimrod__/article/details/126457884