@RequestBody、@RequestParam和 @Pathvariable区别

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

@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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值