@RequestParam
当请求内容相对简单时,可以考虑使用普通参数用于提取请求中的内容
@GetMapping("/single-param-with-annotation")
public String singleParamWithAnnotation(@RequestParam("parameter") String
param) {
//单个必传参数
return "The parameter is :" + param;
}
@PostMapping("/single-param-with-default-value")
public String singleParamWithDefaultValue(@RequestParam(defaultValue =
"default") String param) {
//单个必传参数
return "The parameter is :" + param;
}
@PostMapping("/few-params-with-annotation")
public String fewParamsWithAnnotation(@RequestParam String paramA,
@RequestParam(required = false) Integer paramB) {
//paramA 必传,paramB 可选
return String.format("paramA is :%s,paramB is :%s", paramA, paramB);
}
@RequestParam注解为可选项,不使用也不会影响参数的映射,不过它提供了三个非常实用的属性:name(Web 参数名)、required(是否必传)以及 defaultValue(默认值)。
@RequestParam 的 required 属性默认为 true。这意味着如果未接收到对应参数或对应参数值为 null 的话,接口将会报错。
@PathVariable
使用@PathVariable 获取 URL 中的参数
//单个参数绑定单个入参
@GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id){
return success(equipService.selectEquipById(id));
}
//多个参数绑定多个入参
@GetMapping(value = "/{firstName}/{lastName}", params = MULTI)
@PathVariable("firstName") String firstName, @PathVariable("lastName") String lastName
//多个参数绑定单个 Map
@GetMapping(value = "/{firstName}/{lastName}", params = IN_MAP)
@PathVariable Map<String, String> paramMap
paramMap.get("firstName"),paramMap.get("lastName")
@RequestHeader
借助@RequestHeader 读取请求头
@GetMapping("/greeting")
public String greeting(@RequestHeader("accept-language") String language) {
//根据 Header 中的不同属性返回不同问候语
switch (language) {
case "zh":
return "你好";
case "jp":
return "こんにちは";
case "en":
default:
return "Hello";
}
}
@GetMapping("/header-map")
public String headerMap(@RequestHeader Map<String, String> headers) {
//返回一个由所有头属性拼接而成的字符串
return headers
.entrySet()
.stream()
.map(entry -> String.format("key=%s,value=%s", entry.getKey(),
entry.getValue()))
.collect(Collectors.joining("\r\n"));
}
@RequestBody 与@ResponseBody
这一对注解分别代表着将请求体的内容反序列化为对应类实例(@RequestBody)以及将返回 实例序列化为 JSON 字符串(@ResponseBody),在 Restful 服务的开发过程中非常常见。