SpringBoot实现GET传参和POST传参

649 阅读2分钟

前言

🧐

今天整理一下SpringBoot中GET方法和POST方法传参的基本写法。

GET方法传参

1. 使用到的注解:

  • @RestController: 用于标识这是一个控制层类,其中定义的方法返回的数据会自动转换为JSON格式。简化了@Controller@ResponseBody的使用
  • @RequestMapping: 用于映射请求URL到特定的处理器函数。
  • @GetMapping: 是@RequestMapping(method = RequestMethod.GET)的缩写,用于处理HTTP GET请求。
  • @RequestParam: 用于获取请求参数的值。

2. 注解的用法:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @GetMapping("/get")
    public String get(@RequestParam String name, @RequestParam int age) {
        return "Name: " + name + ", Age: " + age;
    }
}

示例代码解释:

  • @RestController注解在类MyController上,表示这是一个RESTful风格的控制器。
  • @GetMapping("/get")注解在get方法上,表示该方法处理路径为/get的GET请求。
  • @RequestParam注解在get方法的参数nameage上,表示从请求参数中获取nameage的值。

POST方法传参

1. 使用到的注解:

  • @PostMapping: 是@RequestMapping(method = RequestMethod.POST)的缩写,用于处理HTTP POST请求。
  • @RequestBody: 用于获取请求体中的数据,并自动绑定到方法的参数上,通常用于处理JSON数据。

2. 注解的用法:

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @PostMapping("/post")
    public String post(@RequestBody MyData data) {
        return "Received data: " + data.toString();
    }

    static class MyData {
        private String name;
        private int age;

        // getters and setters

        @Override
        public String toString() {
            return "MyData{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}

示例代码解释:

  • @PostMapping("/post")注解在post方法上,表示该方法处理路径为/post的POST请求。
  • @RequestBody注解在post方法的参数data上,表示从请求体中获取数据,并自动转换为MyData类型的对象。
  • MyData是一个简单的Java类,用于接收POST请求体中的JSON数据。

注意:

  • 当使用@RequestParam接收GET请求的参数时,这些参数会被附加到URL上。
  • 当使用@RequestBody接收POST请求的参数时,通常这些数据会被包含在请求体中,并且往往以JSON格式传输。

最后

下次见咯 (●'◡'●)