spring boot 入参方式

方式:

1)、直接写,如public User index2(String name) 

2)、@RequestParam

  与直接写的区别是,可以写默认值。

3)、@RequestBody

   因为传入的是String类型的json,所以可以使用String类型,如:@RequestBody String jsonStr

  当然,也可以使用相应的对象类型。

4)、@PathVariable

  url中{}

例子:

1)、直接写

@RestController
public class UserController {
    @GetMapping("/index")
    public User index(String name) {
        log.info("接收:{}",name);
        return new User(RandomUtil.randomInt(100),String.format("【入参=String】:%s", name));
    }
}

2)、@RequestParam

@GetMapping("/index2")
public User index2(@RequestParam(value="name",defaultValue="World") String name) {
    log.info("接收:{}",name);
    return new User(RandomUtil.randomInt(100),String.format("【入参=@RequestParam】:%s", name));
}

3)、@RequestBody--String

@RequestMapping("/index3")
public User index3(@RequestBody String jsonStr) {
    log.info("接收:{}",jsonStr);
    return new User(RandomUtil.randomInt(100),String.format("【入参=@RequestBody(String)】:%s", jsonStr));
}

3)、@RequestBody--对象

 

@RequestMapping("/index4")
public User index4(@RequestBody User user) {
    log.info("接收:{}",user);
    return new User(RandomUtil.randomInt(100),String.format("【入参=@RequestBody(对象)】:%s", user));
}

4)、@PathVariable

@RequestMapping("/index5/{id}")
public User index5(@PathVariable("id") long id) {
    log.info("接收:{}",id);
    return new User(RandomUtil.randomInt(100),String.format("【入参=@RequestBody】:%s", id));
}

 

posted @ 2019-02-02 18:39  遥远2  阅读(554)  评论(0编辑  收藏  举报