ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-05-25 10:02:21  阅读:208  来源: 互联网

标签:www RequestParam form application json 接收 name


关于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

标签:www,RequestParam,form,application,json,接收,name
来源: https://blog.csdn.net/weixin_43543882/article/details/117248532

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有