SpringBoot—请求处理参数注解

166 阅读1分钟

SpringBoot的接口参数有很多,下面分析一下各个请求的参数注解。

@PathVariable

获取路径上的变量,也可以使用Map接口直接存储所有的接口,自动复制键和值;

接口代码:

@RestController
public class ParameterTestController {

    @GetMapping("/student/{id}/name/{username}")
    public Map<String, Object> getStudent( @PathVariable("id") Integer id,
                                            @PathVariable("username") String name,
                                          @PathVariable Map<String, String> pv ) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("name", name);
        map.put("pv", pv);
        return map;
    }
}

接口返回的信息如下:

{
    "pv": {
        "id": "3",
        "username": "zhangsan"
    },
    "name": "zhangsan",
    "id": 3
}
  • 使用此参数可以直接获得url路径上的参数信息
  • 使用Map,可以直接获得所有的参数,可以不单独写

@RequestHeader

获取请求头的数据

接口代码:

@RestController
public class ParameterTestController {

    @GetMapping("/student/{id}/name/{username}")
    public Map<String, Object> getStudent(@RequestHeader("user-agent") String userAgent,
                                      @RequestHeader Map<String, String> header ) {
        Map<String, Object> map = new HashMap<>();
        map.put("userAgent", userAgent);
        map.put("header", header);
        return map;
    }
}

接口返回信息:

{
    "header": {
        "user-agent": "apifox/1.0.0 (https://www.apifox.cn)",
        "accept": "*/*",
        "host": "localhost:8080",
        "accept-encoding": "gzip, deflate, br",
        "connection": "keep-alive",
        "content-type": "multipart/form-data; boundary=--------------------------625630180057952858863980",
        "content-length": "274"
    },
    "userAgent": "apifox/1.0.0 (https://www.apifox.cn)"
}
  • 此接口获取请求头数据
  • 使用map可以获得全部的数据。

@RequestParam

获取请求参数

接口代码:

@RestController
public class ParameterTestController {

    @GetMapping("/student/{id}/name/{username}")
    public Map<String, Object> getStudent(
                                      @RequestParam("age") Integer age,
                                      @RequestParam("inter") List<String> inter,
                                      @RequestParam Map<String, String> params
                                      ) {
        Map<String, Object> map = new HashMap<>();
        map.put("age", age);
        map.put("inter", inter);
        map.put("params", params);
        return map;
    }
}

接口返回结果:

{
    "inter": [
        "basketball"
    ],
    "params": {
        "age": "18",
        "inter": "basketball"
    },
    "age": 18
}
  • 可以看到使用此注解可以接受post或者get请求的参数,或者使用map进行返回结果。

@PostMapping

获取请求体中的数据

接口代码:

@RestController
public class ParameterTestController {
   
    @PostMapping("/save")
    public Map postMethod(@RequestBody String content) {
        Map<String, Object> map = new HashMap<>();
        map.put("content", content);
        System.out.println(map);
        // {content={"userName=zhangsan","email=dddf"}}
        return map;
    }
}

image.png