SpringBoot实现前后端数据交互、json数据交互、Controller接收参数的几种常用方式

1.获取参数的集中常见注解

  • @PathVariable:一般我们使用URI template样式映射使用,即url/{param}这种形式,也就是一般我们使用的GET,DELETE,PUT方法会使用到的,我们可以获取URL后所跟的参数。
  • @RequestParam:一般我们使用该注解来获取多个参数,在()内写入需要获取参数的参数名即可,一般在PUT,POST中比较常用。
  • @RequestBody:该注解和@RequestParam殊途同归,我们使用该注解将所有参数转换,在代码部分在一个个取出来,也是目前我使用到最多的注解来获取参数

2.获取请求路径参数

  1. get请求,url路径传参
    get请求一般通过url传参,如:

http://localhost:8080/piano/add?brand="xinde" & price = "1200"
后端要获取这些参数,可以使用@RequestParam注解


@RestController
public class HelloController {
    @RequestMapping(value="/hello",method= RequestMethod.GET)
    public String sayHello(@RequestParam Integer id){
        return "id:"+id;
    }

  1. get请求,url路径参数

http://localhost:8080/piano/xinde/buyaoq/1200

后端可以使用@PathVariable接收路径参数

@RestController
public class HelloController {
    @RequestMapping(value="/piano/{brand}/{price}",method= RequestMethod.GET)
    public String sayHello(@PathVariable("price") Integer id,@PathVariable("name") String name){
        return "id:"+id+" name:"+name;
    }
}
posted @ 2020-03-25 11:12  两小无猜  阅读(1576)  评论(0编辑  收藏  举报