application/x-www-form-urlencoded与application/json

2021/5/25 10:26:15

本文主要是介绍application/x-www-form-urlencoded与application/json,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

关于SpringBoot Controller接收前端参数的问题,以及如何配置@Api、@ApiImplicitParam等参数写出一个漂亮的swagger。
总结如下:

1、前端使用application/json发送数据时:

1)请求类型为GET
后端可用@RequestParam接收,@RequestParam可设置多个。
此种方式接收可灵活拓展参数个数,无需另写类进行接收。

@ApiOperation(value = "我的信息", notes = "我的信息")
@ApiImplicitParams({
	@ApiImplicitParam(value = "姓名", name = "name"),
	@ApiImplicitParam(value = "性别", name = "gender")
})
@GetMapping("/user")
public AjaxResult userInfo(
	@RequestParam(required = false) String name,
	@RequestParam(required = true) String gender) {
    return AjaxResult.success();
}

2)请求类型为POST
后端需用@RequestBody + 类名进行接收,使用@RequestParam直接使用类名无法接收到参数。
此种方式接收参数需要单独写实体类进行接收,并在实体类内使用@ApiModel、@ApiModelProperty注解配置swagger,非常不灵活。

@ApiOperation(value = "我的信息", notes = "我的信息")
@PostMapping("/user")
public AjaxResult userInfo(@RequestBody User user) {
    return AjaxResult.success();
}

如果你想拥有一个灵活优雅的swagger文档,请使用application/x-www-form-urlencoded进行数据传输

2、前端使用application/x-www-form-urlencoded发送数据时:

请求类型为GET或POST时
后端均可用@RequestParam接收,@RequestParam可设置多个。
此种方式接收可灵活拓展参数个数,无需另写类进行接收。
由此可见,使用application/x-www-form-urlencoded你可以写出一个灵活统一风格的swagger。

@ApiOperation(value = "我的信息", notes = "我的信息")
@ApiImplicitParams({
	@ApiImplicitParam(value = "姓名", name = "name"),
	@ApiImplicitParam(value = "性别", name = "gender")
})
@GetMapping("/user")
public AjaxResult userInfo(
	@RequestParam(required = false) String name,
	@RequestParam(required = true) String gender) {
    return AjaxResult.success();
}

补充:
1)Chrome开发者工具显示的请求类型
GET方式:统一为 Query String Parameters
POST方式:
application/x-www-form-urlencoded: Form Data
application/json: Request Payload

2)拓展资料
1.application/x-www-form-urlencoded
当action为get时候,浏览器用x-www-form-urlencoded的编码方式把form数据转换成一个字串(name1=value1&name2=value2…),然后把这个字串append到url后面,用?分割,加载这个新的url。
当action为post时候,浏览器把form数据封装到http body中,然后发送到server。
2.application/json
有的时候发现 ajax请求中 content-type:application/json,这样也能在后台接受前台提交的数据,其实这个时候前端提交的数据是 json格式的字符串,后端要用@requestbody注解来接收。
原文链接:https://blog.csdn.net/java_xxxx/article/details/81205315



这篇关于application/x-www-form-urlencoded与application/json的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程