@PathVariable @RequestParam @RequestBody 的作用

@PathVariable

当使用@RequestMapping URI template 样式映射时,@PathVariable能使传过来的参数绑定到路由上,这样比较容易写出restful api

demo1:单参    url : http://127.0.0.1:8080/good/100

@RequestMapping("/test/{id}")

public int test(@PathVariable int id) {

    return id;

}

demo2:多参    url : http://127.0.0.1:8080/test/10/100

@RequestMapping("/test/{type}/{id}")

public String test(@PathVariable long type, @PathVariable long id) {

    return type+","+id;

}

@RequestParam

接收的参数是来自HTTP请求体或请求url的QueryString中,使用该注解时Content-Type字段,需要为application/x-www-form-urlencoded,同时,支持post和get

demo1:最简单的,URL中的key与形参一致   url : http://127.0.0.1:8080/test?id=100

@RequestMapping("/test")

public int test01(@RequestParam(required = true, defaultValue = "0") int id) {

    return id;

}

demo2:URL中的key与形参不一致    url : http://127.0.0.1:8080/test?uid=100

@RequestMapping("/test")

public int test02(@RequestParam(value = "uid", defaultValue = "0") int id) {

    return id;

}

demo3:URL中一个key有多个值    url : http://127.0.0.1:8080/test?id=100&id=200

@RequestMapping("/test")

public String test03(@RequestParam(value="id") long[] id){

    System.out.println(id);

    return "";

}

//或者是

@RequestMapping("/test")

public String test04(@RequestParam(value="list") List<Integer> list){

    System.out.println(list);

    return "";

}

demo4:一般使用map集合来接受多参    url : http://127.0.0.1:8080/test?id=100&name=tom

@RequestMapping("/test")

public String test01(@RequestParam Map params){

    String name = params.get("name").toString();

    return name;

}

@RequestBody

该注解常用于接受请求体中非application/x-www-form-urlencoded编码格式的数据,比如:application/json、application/xml,现在前后端分离系统那么多,所以这才是主角。

总之

/{id}这种传参形式可以用形式@PathVariable

url中的?后面参数可以用@RequestParam, form-data、x-www-form-urlencoded可以用@RequestParam

application/json:json字符串可以用@RequestBody

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容