By far the most complete spring boot parameter transfer scheme in the whole network

Keywords: Front-end JSON Java Mobile xml

Preface

After so many years of development, there must be a lot of small partners who can't figure out how to transfer various types of parameters. Many students are just using them and copying and pasting them. They are still confused when they encounter problems.

posture

Learn the correct posture of parameter transfer, first say how to do it, then why, in essence, copy and paste a roll, the question is whether you want to ask why!

transmit

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);

    /**
     * Sign in
     */
    @PostMapping("/login")
    public Result login(String username, String password){
        logger.info("User login"+username);
        //Business logic
        return Result.ok("Login successfully");
    }
}

Of course, you can also do this, @ RequestParam(value="username", required=true), and required is true by default. 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, the default value is null.

/**
  * Sign in
  * 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 successfully");
}

User registration

The front-end code and submission method are basically the same as the login.

Back end code:

An object is used to receive foreground parameters. Generally, the backend has corresponding entity classes.

/**
  * register
  * https://blog.52itstyle.vip
  */
@PostMapping("/register")
public Result register(SysUser user){
    logger.info("{},User registration",user.getUsername());
    //Business logic
    return Result.ok("login was successful");
}

Multi parameter no entity one

Front end code:

var param = {
    "title": "Java notes",
    "content": "An interesting public address.",
    "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("Multiparameter transfer:{},{}",map.get("title"),map.get("content"));
    //Business logic
    return Result.ok("Successfully received multiple parameters");
}

Multiparameter no entity two

Front end code:

var param = {
    "title": "Java notes",
    "content": "An interesting public address.",
    "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("Multiparameter transfer:{},{}",map.get("title"),map.get("content"));
    //Business logic
    return Result.ok("Successfully received multiple parameters");
}

Transfer 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:

/**
  * array
  * https://blog.52itstyle.vip
  */
@PostMapping("array")
public Result array(@RequestParam(value = "ids[]") Integer[] ids) {
    logger.info("data{}", Arrays.asList(ids));
    //Business logic
    return Result.ok();
}

Transitive set

The front-end code is consistent with the passed array.

Back end implementation:

/**
  * aggregate
  * https://blog.52itstyle.vip
  */
@PostMapping("array")
public Result array(@RequestParam(value = "ids[]") List<Integer> ids) {
    logger.info("data{}", ids.toString());
    //Business logic
    return Result.ok();
}

Transferring collection entity objects

For example, the backend wants to receive a collection of entity objects list < sysuser >

Front end code:

var list = [];
list.push({
    "username": "Xiao Qi 2012",
    "mobile": "17762288888"
});
list.push({
    "username": "Xiao Qi 2013",
    "mobile": "17762289999"
});
$.ajax({
    url: "/sys/listUser",
    data: JSON.stringify(list),
    type: "post",
    contentType: "application/json",
    dataType: "json",
    success: function(data) {

    }
});

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->{
      //Export solid objects
      System.out.println(user.getUsername());
   });
   //Business logic
   return Result.ok();
}

Transfer collection entity objects one to many

For example, a user has multiple roles list < sysrole > rolelist

Front end code:

var roleList = [];
roleList.push({
    "roleSign": "admin",
    "roleName": "Administrators"
});
roleList.push({
    "roleSign": "user",
    "roleName": "Ordinary users"
});
var list = [];
var user = {
    "username": "Xiao Qi 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:

/**
  * Java notes
  * https://blog.52itstyle.vip
  */
@PostMapping("listUserRole")
public Result listUserRole(@RequestBody List<SysUser> list) {
    logger.info("data{}", list.size());
    list.forEach(user->{
        List<SysRole> roleList = user.getRoleList();
        roleList.forEach(role->{
          System.out.println(role.getRoleName());
        });
    });
    return Result.ok();
}

Scrambled chicken complex

There are entities, collections and various types of data in the transmission object. At this time, the simplest way is to pass the JSON string of the key value structure, which is received by the background Map type, and then convert it to the corresponding entity or collection through FastJson's JSON.parseObject(), JSON.parseArray().

 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, visit an article:

/**
  * Java notes
  * https://blog.52itstyle.vip
  */
@GetMapping("article/{id}")
public void article(@PathVariable("id") String id) {
    logger.info("Article{}",id);
    //Business logic
}

Principle

Remember the following:

  • @RequestBody annotation must be used with contentType type application/json.
  • @RequestParam annotation must be used with contentType type application/x-www-form-urlencoded, which is the default type.
  • JSON.stringify(), which converts object type to string type, is generally used with @ RequestBody annotation and contentType type application/json.

extend

There are only two types of contentType mentioned above, but there are also two common types:

multipart/form-data

Generally used for form file upload, the enctype of the form must be equal to this value.

<form action="/upload" method="post" enctype="multipart/form-data">
  <input type="text" name="description" value="Java notes, a magical public address">
  <input type="file" name="myFile">
  <button type="submit">Submit</button>
</form>

text/xml

The little partners who have done wechat payment will know that wechat likes to use this method. Last year, there was a ‚ XXE ‚ vulnerability. When parsing XML documents, the parser reads the local protected files through the ENTITY extension function, and uses the extension function to send the protected files to the remote address.

Summary

I dare not say that it is the most complete parameter transmission scheme, but I absolutely dare to guarantee that it is the most correct, because all the methods of parameter transmission have passed the 360 ° official test.

 

>>Alibaba cloud's subsidy of RMB 1.1 billion will be collected in advance, and the iPhone 11 Pro will be extracted.

 

Read the original text

This is the original content of yunqi community, which can not be reproduced without permission.

Posted by Owe Blomqvist on Tue, 29 Oct 2019 20:53:10 -0700