Foreword
Development for so many years, how sure there are many small partners confuse the various types of parameters are passed, many students are brought ready to use, copy and paste a line and encounter problems or look ignorant force.
posture
Learn the correct posture parameter passing, first say how to do, and what with, in essence, is to copy and paste a line and the problem is you do not want to ask to ask why!
transfer
User login
Front-end code:
var param = {
"username": "admin",
"password": "admin"
}
$.ajax({
url: "/sys/login",
data: param,
type: "post",
dataType: "json",
success: function(data) {
}
});
Back-end code:
@RestController
@RequestMapping("/sys")
public class LoginController {
private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
/**
* 登录
*/
@PostMapping("/login")
public Result login(String username, String password){
logger.info("用户登录"+username);
//业务逻辑
return Result.ok("登录成功");
}
}
Of course, you can also be so implemented @RequestParam(value="username", required=true)
, required
by default true
, do not pass this parameter if the foreground, the background error. If set to false
, if not pass, the default is null
.
/**
* 登录
* https://blog.52itstyle.vip
*/
@PostMapping("/login")
public Result login(@RequestParam(value="username", required=true) String username,
@RequestParam(value="password", required=true) String password){
logger.info("用户登录"+username);
//业务逻辑
return Result.ok("登录成功");
}
User Registration
Front-end code, submission login remained the same.
Back-end code:
Reception parameters to receive an object, typically the rear end of a corresponding entity class.
/**
* 注册
* https://blog.52itstyle.vip
*/
@PostMapping("/register")
public Result register(SysUser user){
logger.info("{},用户注册",user.getUsername());
//业务逻辑
return Result.ok("注册成功");
}
A multi-parameter non-entity
Front-end code:
var param = {
"title": "爪哇笔记",
"content": "一个有趣的公众号",
"author": "小柒2012"
}
param = JSON.stringify(param);
$.ajax({
url: "/sys/multiParameter",
data: param,
type: "post",
contentType: "application/json",
dataType: "json",
success: function(data) {
}
});
Back-end implementation:
/**
* 多参数
* https://blog.52itstyle.vip
*/
@PostMapping("/multiParameter")
public Result register(@RequestBody Map<String,Object> map){
logger.info("多参数传递:{},{}",map.get("title"),map.get("content"));
//业务逻辑
return Result.ok("接收多参数成功");
}
Multi-parameter no two entities
Front-end code:
var param = {
"title": "爪哇笔记",
"content": "一个有趣的公众号",
"author": "小柒2012"
}
$.ajax({
url: "/sys/multiParameter",
data: param,
type: "post",
dataType: "json",
success: function(data) {
}
});
Back-end implementation:
/**
* 多参数
* https://blog.52itstyle.vip
*/
@PostMapping("/multiParameter")
public Result register(@RequestParam Map<String,Object> map){
logger.info("多参数传递:{},{}",map.get("title"),map.get("content"));
//业务逻辑
return Result.ok("接收多参数成功");
}
Passing arrays
Front-end code:
var param = {
"ids": [1, 2, 3]
}
$.ajax({
url: "/sys/array",
data: param,
type: "post",
dataType: "json",
success: function(data) {
}
});
Back-end implementation:
/**
* 数组
* https://blog.52itstyle.vip
*/
@PostMapping("array")
public Result array(@RequestParam(value = "ids[]") Integer[] ids) {
logger.info("数据{}", Arrays.asList(ids));
//业务逻辑
return Result.ok();
}
Passing Collections
The front end transmission code consistent array.
Back-end implementation:
/**
* 集合
* https://blog.52itstyle.vip
*/
@PostMapping("array")
public Result array(@RequestParam(value = "ids[]") List<Integer> ids) {
logger.info("数据{}", ids.toString());
//业务逻辑
return Result.ok();
}
Passing Collections entity objects
For example, the rear end would like to receive a collection of entity objects List<SysUser>
Front-end code:
var list = [];
list.push({
"username": "小柒2012",
"mobile": "17762288888"
});
list.push({
"username": "小柒2013",
"mobile": "17762289999"
});
$.ajax({
url: "/sys/listUser",
data: JSON.stringify(list),
type: "post",
contentType: "application/json",
dataType: "json",
success: function(data) {
}
});
Back-end code:
/**
* 爪哇笔记
* https://blog.52itstyle.vip
*/
@PostMapping("listUser")
public Result listUser(@RequestBody List<SysUser> list) {
logger.info("数据{}", list.size());
list.forEach(user->{
//输出实体对象
System.out.println(user.getUsername());
});
//业务逻辑
return Result.ok();
}
Many objects passing collection of entities
For example, a user has multiple roles List<SysRole> roleList
Front-end code:
var roleList = [];
roleList.push({
"roleSign": "admin",
"roleName": "管理员"
});
roleList.push({
"roleSign": "user",
"roleName": "普通用户"
});
var list = [];
var user = {
"username": "小柒2012",
"mobile": "17762288888"
};
user.roleList = roleList;
list.push(user);
$.ajax({
url: "/sys/listUserRole",
data: JSON.stringify(list),
type: "post",
contentType: "application/json",
dataType: "json",
success: function(data) {
}
});
Back-end implementation:
/**
* 爪哇笔记
* https://blog.52itstyle.vip
*/
@PostMapping("listUserRole")
public Result listUserRole(@RequestBody List<SysUser> list) {
logger.info("数据{}", list.size());
list.forEach(user->{
List<SysRole> roleList = user.getRoleList();
roleList.forEach(role->{
System.out.println(role.getRoleName());
});
});
return Result.ok();
}
Chicken complicated
Transport object entities, there is a collection, various types of data, this time is the easiest way to transfer Key-Value
structure JSON
string, the background Map
type received, then FastJson
the JSON.parseObject()
and JSON.parseArray()
converted to the corresponding entity or collection.
String user = parseMap.get("user").toString();
SysUser sysUser = JSON.parseObject(user,SysUser.class);
String contractClause = parseMap.get("rules").toString();
List<Rule> ruleList = JSON.parseArray(contractClause,Rule.class);
RESTful style
For example, to access an article:
/**
* 爪哇笔记
* https://blog.52itstyle.vip
*/
@GetMapping("article/{id}")
public void article(@PathVariable("id") String id) {
logger.info("文章{}",id);
//业务逻辑
}
in principle
Remember the following points:
@RequestBody
Notes, must becontentType
the typeapplication/json
used in conjunction.@RequestParam
Notes, must becontentType
the typeapplication/x-www-form-urlencoded
used in conjunction, which is the default type.JSON.stringify()
Converted to a string object type, with the general@RequestBody
annotation andcontentType
type ofapplication/json
use.
Spread
In the above involves only two contentType
types, in fact, there are two common types:
multipart/form-data
enctype generally used for file upload form, must be allowed to form equal to this value.
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="text" name="description" value="爪哇笔记,一个神奇的公众号">
<input type="file" name="myFile">
<button type="submit">Submit</button>
</form>
text/xml
Done a micro-channel pay little friends will know that you like to use micro-channel in this way, also happened last year XXE
loopholes when parsing an XML document, the parser by ENTITY extended functionality, read the local protected files, and using the extended function sends a protected file to a remote address.
summary
I can not say is the most complete mass participation program, but the absolute guarantee that the most correct, because all the way to pass parameters have been 360 ° official inspection.