一、认识REST

REST(英文:Representational State Transfer,简称 REST)
        一种互联网软件架构设计的风格,但它并不是标准,它只是提出了一组客户端和服务器交互时的架构理念和设计原则,基于这种理念和原则设计的接口可以更简洁,更有层次,REST 这个词,是 Roy Thomas Fielding 在他 2000 年的博士论文中提出的。
      任何的技术都可以实现这种理念,如果一个架构符合 REST 原则,就称它为 RESTFul 架构
      比如我们要访问一个 http 接口:http://localhost:8080/boot/order?id=1021&status=1
      采用 RESTFul 风格则 http 地址为:http://localhost:8080/boot/order/1021/1

1.REST中的要素:

       用REST表示资源和对资源的操作。  在互联网中,表示一个资源或者一个操作。资源使用url表示的, 在互联网, 使用的图片,视频, 文本,网页等等都是资源。 资源是用名词表示。

       资源使用url表示,通过名词表示资源。在url中,使用名词表示资源, 以及访问资源的信息,  在url中,使用“ / " 分隔对资源的信息。

2.注解

  @PathVariable :  从url中获取数据

  @GetMapping:    支持的get请求方式,  等同于 @RequestMapping( method=RequestMethod.GET)

  @PostMapping:  支持post请求方式 ,等同于 @RequestMapping( method=RequestMethod.POST)

  @PutMapping:  支持put请求方式,  等同于 @RequestMapping( method=RequestMethod.PUT)

   @DeleteMapping: 支持delete请求方式,  等同于 @RequestMapping( method=RequestMethod.DELETE)

  @RestController:  符合注解, 是@Controller 和@ResponseBody组合。 在类的上面使用@RestController , 表示当前类者的所有方法都加入了 @ResponseBody。

项目结构

1.pom.xml文件只加入web起步依赖就可以了

2.controller包下的MyRestController类

package com.it.controlller;

import org.springframework.web.bind.annotation.*;

@RestController
public class MyRestController {


    //查询id是等于1001的学生
    /*
    @PathVariable(路径变量):获取url中的数据
                属性:  value:定义路径变量名称
                位置:   放在控制器方法的形参的前面

                {id}:定义路径变量,stuId自定义名称
     */

    @GetMapping("/student/{id}")
    public String queryStudent(@PathVariable(value = "id") Integer studentId){
        return "查询学生studentId="+studentId;
    }


    /***
     * 创建资源Post请求方式
     *
     */
    @PostMapping("/student/{name}/{age}")
    public String createStudent(@PathVariable("name") String name,
                                @PathVariable("age") Integer age){
        return "创建资源 student:name="+name+" age="+age;
    }

    /**
     * 更新资源
     * 当@PathVariable中的路径变量名称和形参名一样,@PathVariable中的形参名可以省略
     */
    @PutMapping("/student/{id}/{age}")
    public String modifyStudent(@PathVariable Integer id,@PathVariable Integer age){
        return "更新资源,执行put请求方式:  id="+id+" age="+age;
    }


    /**
     * 删除资源
     *
     */
    @DeleteMapping("/student/{id}")
    public String removeStudentById(@PathVariable Integer id){
        return "删除资源,执行delete,id="+id;
    }

    


}

3.测试post时需要用到表单addStudent.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h3>添加学生</h3>
    <form action="student/zhangshan/20" method="post">
        <input type="submit" value="注册学生">
    </form>
</body>
</html>

4.application.properties文件

server.port=9003
server.servlet.context-path=/myboot

 5.运行主函数入口,分别测试这四种注解

@GetMapping

这种方式可以直接在网站的url地址栏中编写

@PostMapping

这种方式需要借助表单,进行传输。首先进入html页面,点击注册学生进行传输数据

 

@PutMapping

这种方式无法在网站的url地址栏中直接发送请求,需要借助postman工具进行传送请求

@DeleteMapping

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐