The parameter binding of basic application of springboot2 can correctly understand the scope of content type

Keywords: Programming JSON xml Attribute Java

Content type understanding

http protocol is an application layer protocol based on tcp/ip protocol, which consists of three parts: status line, header information and message body. The corresponding http request is: request line, request header, request body.

The content type is in the request header. Generally, the server will obtain how the parameters are encoded according to the content type field, and then decode them accordingly;

Common resource types for form submission or upload:

  1. application/x-www-form-urlencoded (default)
  2. multipart/form-data,
  3. application/json,
  4. application/xml

The enctype attribute can be defined in the form form, which means how to code the form data before sending it to the server.

By default, the form data is encoded as "application / x-www-form-ignored"

The common attribute values of enctype are as follows: application / x-www-form-unencoded: encode all characters before sending (by default);
Multipart / form data, no character encoding. Use this value when using file uploads.

 

For nested arrays or complex formats in the request body, it is recommended to use application/json for transmission. Back-end parsing will be more convenient, and data will be sent to the server in the form of json.

The advantage of json form is that it can transfer data form with complex structure

 

Parameter binding

Parameter transfer can be said to be the main way for the server to communicate with the outside world. This section is very important!
 

Pass parameters through url
    |---get method Url parameter
        |---@PathVariable is in the form of url/id/1994
        |---@RequestParam: url?username=zed
    |---POST mode parameters
        |---@RequestParam
        |---Add text to request body
Profile parameters

get method Url parameters:

@PathVariable

@RestController
public class HelloController {
    @GetMapping("/hello/{name}")
    public String hello(@PathVariable("name") String name){
        // The name of a parameter is optional
        System.out.println("Acquired name Yes,"+name);
        return "hello "+name;
    }
}

get method Url parameters:

@RequestParam

If the name of the request parameter is the same as the parameter name in the method, @ RequestParam("name") can be omitted

@GetMapping("/hello")
public String hello(@RequestParam("name") String name){
    System.out.println("Acquired name Yes,"+name);
    return "hello "+name;
}

3.get method Url parameter:

@RequestParam + default parameters

@GetMapping("/hello")
    public String hello(@RequestParam(value = "name",defaultValue = "admin") String name){
        System.out.println("Acquired name Yes,"+name);
        return "hello "+name;
    }

Note: if no default value is specified and no parameter is passed, an error will be reported

Required string parameter 'name' is not present: the name parameter is not provided

  • Solution
    • 1.defaultValue = "xxx": use default value
    • 2.required = false: annotation parameter is not required
@GetMapping("/hello")
public String hello(@RequestParam(value = "name",required = false) String name){
    System.out.println("Acquired name Yes,"+name);
    return "hello "+name;
}

POST mode to transfer data

@RestController
public class HelloController {
    public static Logger log = LoggerFactory.getLogger(HelloController.class);

    @PostMapping("/user")
    public String add(@RequestParam("name") String name,@RequestParam("age") Integer age){
        log.info(name+"  "+age);
        return "name:"+name+"\nage:"+age;
    }
}

POST passes string text

@PostMapping("/PostString")
public String postString(HttpServletRequest request) {
    ServletInputStream is = null;
    try {
        is = request.getInputStream();
        StringBuilder sb = new StringBuilder();
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = is.read(buf)) != -1) {
            sb.append(new String(buf, 0, len));
        }
        System.out.println(sb.toString());
        return sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

@requestbody receive parameter

@PostMapping("/save")
@ResponseBody
public Map<String,Object> save(@RequestBody User user){
    Map<String,Object> map = new HashMap<String,Object> ();
    map.put("user",user);
    return map;
}
@PostMapping("/user")
public String user(@RequestBody User user){
    log.info(user.toString());
    return null;
}

For more information, please refer to the original text: https://www.jianshu.com/p/ad13fc37b047

case

package top.qsou.test.demo.controller;

import org.springframework.web.bind.annotation.*;
import top.qsou.test.demo.dto.User;

import java.awt.print.Pageable;

@RestController
@RequestMapping("/param")
public class ParamController {
    /**
     *  url Direct transmission, value can be obtained; @ RequestParam optional
     * @param name
     * @param pass
     * @return
     */
    @GetMapping("test1")
    public Object test01(@RequestParam String name, @RequestParam String pass) {
        System.out.println( name + pass );
        return name + "---------" + pass;
    }

    /**
     * defaultValue Valid, default value exists
     * @param name
     * @param pass
     * @return
     */
    @GetMapping("test1-1")
    public Object test02(@RequestParam(defaultValue = "wxw") String name,String pass) {
        System.out.println( name + pass );
        return name + "---------" + pass;
    }

    /**
     * form-data When submitted: available
     * x-www-urlencoded When submitted: available
     * raw json When the body format is submitted: cannot get, must use @ RequestBody annotation to get
     * @param user
     * @return
     */
    @PostMapping("test2")
    public Object test04(User user) {
        return user.getName() + "---------" + user.getPass();
    }

    /**
     * Must be received in json body format
     * @param user
     * @return
     */
    @PostMapping("test2-1")
    public Object test05(@RequestBody User user) {
        return user.getName() + "---------" + user.getPass();
    }

    /**
     * form-data When submitted: available
     * x-www-urlencoded When submitted: available
     * raw json When body format is submitted: cannot get
     * @param name
     * @param pass
     * @return
     */
    @PostMapping("test2-3")
    public Object test042(@RequestParam String name,String pass) {
        return name+ "-----------------"+pass;
    }
}

 

Key points: underline

Difference between multipart / form data and x-www-form-urlencoded

Multipart / form data: you can upload binary data such as files or key value pairs of forms, but it will be converted into a piece of information finally;

x-www-form-urlencoded: only key value pairs can be uploaded, and the key value pairs are separated. For example, name = Java & age = 23; special characters need to be escaped to utf-8 number, for example, the space will become% 20

raw

You can upload text in any format, such as text, json, xml, html, etc

Please refer to the article for more details: https://blog.csdn.net/pomer_huang/article/details/79495346 

Posted by tisource on Wed, 06 Nov 2019 09:29:31 -0800