SpringBoot Setting Incoming Parameters Non essential Actions
- 2021-08-31 07:46:48
- OfStack
I won't talk too much, let's just look at the code ~
Set whether the parameter is required
@RequestParam(required = false)
Supplement: Correct gesture of parameter passing in SpringBoot development case
Preface
After so many years of development, there must be many small partners who can't figure out how various types of parameters are transmitted. Many students use them immediately, copy and paste them, and they are still puzzled when they encounter problems.
Posture
Learn the correct posture of parameter transmission, first say how to do it, then say why, in essence, copy and paste a roll, the question is if you want 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);
/**
* Login
*/
@PostMapping("/login")
public Result login(String username, String password){
logger.info(" User login "+username);
// Business logic
return Result.ok(" Login Successful ");
}
}
Of course, you can also do this. @ RequestParam (value= "username", required=true), required defaults to true. If the foreground does not pass this parameter, the background will report an error. If it is set to false, if it is not transmitted, it defaults to null.
/**
* Login
* 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(" User login "+username);
// Business logic
return Result.ok(" Login Successful ");
}
User registration
Front-end code, submission method and login basically keep 1.
Back-end code:
Use 1 object to receive foreground parameters, and 1 backend has corresponding entity classes.
/**
* Registration
* https://blog.52itstyle.vip
*/
@PostMapping("/register")
public Result register(SysUser user){
logger.info("{} User registration ",user.getUsername());
// Business logic
return Result.ok(" Successful registration ");
}
Multi-parameter No Entity 1
Front end code:
var param = {
"title": " Java Notes ",
"content": "1 An interesting WeChat official account ",
"author": " Xiao Qi 2012"
}
param = JSON.stringify(param);
$.ajax({
url: "/sys/multiParameter",
data: param,
type: "post",
contentType: "application/json",
dataType: "json",
success: function(data) {
}
});
Back-end implementation:
/**
* Multi-parameter
* https://blog.52itstyle.vip
*/
@PostMapping("/multiParameter")
public Result register(@RequestBody Map<String,Object> map){
logger.info(" Multi-parameter transfer :{},{}",map.get("title"),map.get("content"));
// Business logic
return Result.ok(" Receive multiple parameters successfully ");
}
Multi-parameter no entity 2
Front end code:
var param = {
"title": " Java Notes ",
"content": "1 An interesting WeChat official account ",
"author": " Xiao Qi 2012"
}
$.ajax({
url: "/sys/multiParameter",
data: param,
type: "post",
dataType: "json",
success: function(data) {
}
});
Back-end implementation:
/**
* Multi-parameter
* https://blog.52itstyle.vip
*/
@PostMapping("/multiParameter")
public Result register(@RequestParam Map<String,Object> map){
logger.info(" Multi-parameter transfer :{},{}",map.get("title"),map.get("content"));
// Business logic
return Result.ok(" Receive multiple parameters successfully ");
}
Passing array
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:
var param = {
"username": "admin",
"password": "admin"
}
$.ajax({
url: "/sys/login",
data: param,
type: "post",
dataType: "json",
success: function(data) {
}
});
0
Passing set
The front-end code keeps 1 with the passing array.
Back-end implementation:
var param = {
"username": "admin",
"password": "admin"
}
$.ajax({
url: "/sys/login",
data: param,
type: "post",
dataType: "json",
success: function(data) {
}
});
1
Passing a collection entity object
For example, the backend wants to receive a collection of entity objects List < SysUser >
Front end code:
var param = {
"username": "admin",
"password": "admin"
}
$.ajax({
url: "/sys/login",
data: param,
type: "post",
dataType: "json",
success: function(data) {
}
});
2
Back-end code:
/**
* Java Notes
* https://blog.52itstyle.vip
*/
@PostMapping("listUser")
public Result listUser(@RequestBody List<SysUser> list) {
logger.info(" Data {}", list.size());
list.forEach(user->{
// Output entity object
System.out.println(user.getUsername());
});
// Business logic
return Result.ok();
}
Passing collection entity objects 1 to many
For example, one user has multiple roles List < SysRole > roleList
Front end code:
var param = {
"username": "admin",
"password": "admin"
}
$.ajax({
url: "/sys/login",
data: param,
type: "post",
dataType: "json",
success: function(data) {
}
});
4
Back-end implementation:
var param = {
"username": "admin",
"password": "admin"
}
$.ajax({
url: "/sys/login",
data: param,
type: "post",
dataType: "json",
success: function(data) {
}
});
5
Fried chicken is complicated
The transmission objects include entities, collections and various types of data. At this time, the simplest way is to pass JSON string with Key-Value structure, receive it with Map type in the background, and then transform it into corresponding entities or collections through JSON. parseObject () and JSON. parseArray () methods of FastJson.
var param = {
"username": "admin",
"password": "admin"
}
$.ajax({
url: "/sys/login",
data: param,
type: "post",
dataType: "json",
success: function(data) {
}
});
6
RESTful Style
For example, visit an article:
var param = {
"username": "admin",
"password": "admin"
}
$.ajax({
url: "/sys/login",
data: param,
type: "post",
dataType: "json",
success: function(data) {
}
});
7
Principle
Remember the following points:
@ RequestBody annotation, must be used with contentType type application/json.
The @ RequestParam annotation must be used with the contentType type application/x-www-form-urlencoded, which is the default type.
JSON. stringify () converts an object type to a string type, which is generally used in conjunction with the @ RequestBody annotation and the contentType type application/json.
Expand
There are only two contentType types mentioned above, but there are actually two common types:
multipart/form-data
1 for form file uploads, you must have enctype of form equal to this value.
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="text" name="description" value=" Java Notes, 1 A magical WeChat official account ">
<input type="file" name="myFile">
<button type="submit">Submit</button>
</form>
text/xml
Partner 1, who has done WeChat payment, will know that WeChat likes to use this method. Last year, there was an XXE vulnerability. When parsing XML documents, the parser reads local protected files through the extended function of ENTITY, and uses the extended function to send the protected files to remote addresses.
Summary
I dare not say that it is the most complete parameter transmission scheme, but I can definitely guarantee that it is the most correct, because all the parameter transmission methods have passed the 360 official test.