@RequestBody、@RequestParam和 @Pathvariable区别
@RequestParam
是接受的参数是来自http请求体或者请求url的QueryString中
参数:
@RequestParam有三个配置参数:
required 表示是否必须,默认为 true,必须。
defaultValue 可设置请求参数的默认值。
value 为接收url的参数名(相当于key值)。
@Controller
@RequestMapping("/pets")
@SessionAttributes("pet")
public class EditPetForm {
// ...
@RequestMapping(method = RequestMethod.GET)
public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
Pet pet = this.clinic.loadPet(petId);
model.addAttribute("pet", pet);
return "petForm";
}
// ...
@Pathvariable
使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可通过 @Pathvariable注解绑定它传过来的值到方法的参数上。
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
@RequestMapping("/pets/{petId}")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
// implementation omitted
}
}
@RequestBody
该注解常用来处理Content-Type: 不是application/x-www-form-urlencoded编码的内容,例如application/json, application/xml等;
它是通过使用HandlerAdapter 配置的HttpMessageConverters来解析post data body,然后绑定到相应的bean上的。
因为配置有FormHttpMessageConverter,所以也可以用来处理 application/x-www-form-urlencoded的内容,处理完的结果放在一个MultiValueMap<String, String>里,这种情况在某些特殊需求下使用,详情查看FormHttpMessageConverter api;
@RequestMapping(value = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body, Writer writer) throws IOException {
writer.write(body);
}
参考:
https://blog.csdn.net/walkerjong/article/details/7946109
https://blog.csdn.net/weixin_38004638/article/details/99655322

这篇博客详细介绍了Spring MVC中三个关键注解——@RequestParam、@PathVariable和@RequestBody的用途和区别。@RequestParam用于从URL的查询字符串或请求体获取参数,@PathVariable则用于获取URI模板中的变量值,而@RequestBody则用于处理非x-www-form-urlencoded编码的内容,如JSON或XML,将请求体的数据绑定到方法参数上。

104万+

被折叠的 条评论
为什么被折叠?



