@RequestParam()和@PathVariable()的使用

 我们看下例子,准备一个请求到后台后面通过携带参数过去 url:http://linfeng.taotao.com/rest/item/cat?id=1

后台在controller中接受为@RequestMapping("/item/cat"),想要获得请求的参数,这个时候用@RequestParam(),注意里面的value表示接受的value是id(如果后面跟的Long parent_id形参名称跟传过来的参数名称一样,RequestParam()里面的value可以不用写(如第二张图),也可以去掉@RequestParam()),如果没有传过来值可以用defaultValue设置默认的值

    @RequestMapping(method=RequestMethod.GET)
    public ResponseEntity<List<ItemCat>> queryItemCat(@RequestParam(value="id",defaultValue="0") Long parent_id){
        if(parent_id==null){
      	ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
        }
        ItemCat itemCat=new ItemCat();
        itemCat.setParentId(parent_id);
        List<ItemCat> list=itemCatService.queryListByWhere(itemCat);
        return ResponseEntity.ok(list);
    }


我们看第二个例子

现在请求的URL可以是“http://linfeng.taotao.com/rest/item/1”或“http://linfeng.taotao.com/rest/item/2”很明显现在这个参数在URL上的数据

@RequestMapping("item/{id}")
@ResponseBody
public Item queryItemById(@PathVariable() Integer id) {
	Item item = this.itemService.queryItemById(id);
	return item;
}
  1. 使用注解@RequestMapping("item/{id}")声明请求的url,{?}的写法是占位符
  2. 使用(@PathVariable() Integer id)获取url上的数据

  3. 如果@RequestMapping中表示为"item/{id}",id和形参名称一致,@PathVariable不用指定名称。如果不一致,例如"item/{ItemId}"则需要指定名称@PathVariable("itemId")


    总结:@PathVariable是获取url上数据的。@RequestParam获取请求参数的(包括post表单提交)

猜你喜欢

转载自blog.csdn.net/linlinlinfeng/article/details/82821384