16

spring-boot-route(一)Controller接收参数的几种方式

 3 years ago
source link: http://www.cnblogs.com/zhixie/p/13762519.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Controller接收参数的常用方式总体可以分为三类。第一类是Get请求通过拼接url进行传递,第二类是Post请求通过请求体进行传递,第三类是通过请求头部进行参数传递。

1 @PathVariable接收参数

请求方式:localhost:7001/param/123

请求示例:

zgbAuWnJ6fly5oi.png

代码示例:

@GetMapping("{id}")
public String getPathVariable(@PathVariable String id){
    return "id="+id;
}

2 @RequestParam接收参数

使用这个注解需要注意两个点,一是加了这个参数后则请求中必须传递这个参数,二是@RequestParam这个注解可以指定名字,请求参数必须和指定的这个名字相同,如果不指定,则默认为具体参数名。

请求方式:localhost:7001/param/getParam?myId=18

请求示例:

wGSs5CmYrdHqvEJ.png

代码示例:

@GetMapping("getParam")
public String getRequestParam(@RequestParam("myId") String id){
    return "id="+id;
}

3 无注解传参

这种方式和2对比,最大的区别就是这个参数不是必传的,请求路径上可以不传递。

请求方式:localhost:7001/param/getString?id=18

请求示例:

2IRjyqr.png!mobile

代码示例:

@GetMapping("getString")
public String getString(String id){
    return "id="+id;
}

4 HttpServletRequest接收参数

请求方式:localhost:7001/param/getRequest?id=18

请求示例:

bQfYbme.png!mobile

代码示例:

@GetMapping("getRequest")
public String getRequest(HttpServletRequest request){
    String id = request.getParameter("id");
    return "id="+id;
}

5 @RequestBody接收请求体参数

这种方式一般用来传递实体对象,加了这个注解后,参数也是必传的。

请求方式:{"id":18}

请求示例:

Nb2mQvz.png!mobile

代码示例:

@PostMapping("getBody")
public String getBody(@RequestBody String id){
    return "id="+id;
}

6 @RequestHeader接收请求头参数

请求示例:

MbIZ3yR.png!mobile

代码示例:

@PostMapping("getHeader")
public String getHeader(@RequestHeader String id){
    return "id="+id;
}

此是spring-boot-route系列的第一篇文章,这个系列的文章都比较简单,主要目的就是为了帮助初次接触Spring Boot 的同学有一个系统的认识。本文已收录至我的 github ,欢迎各位小伙伴 star

github: https://github.com/binzh303/spring-boot-route

点关注、不迷路

如果觉得文章不错,欢迎 关注点赞收藏 ,你们的支持是我创作的动力,感谢大家。

如果文章写的有问题,请不要吝啬,欢迎留言指出,我会及时核查修改。

如果你还想更加深入的了解我,可以微信搜索「 Java旅途 」进行关注。回复「 1024 」即可获得学习视频及精美电子书。每天7:30准时推送技术文章,让你的上班路不在孤独,而且每月还有送书活动,助你提升硬实力!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK