springboot2基础运用之参数绑定, 正确理解Content-type的做用范围

Content-Type的理解

http协议是创建在tcp/ip协议之上的应用层协议,主要包括三个部分,状态行,头部信息,消息主体。对应一个http请求就是:请求行,请求头,请求体。html

content-type就在请求头中 . 通常服务端会根据content-type字段来获取参数是怎么编码的,而后对应去解码;java

表单提交或上传文件的经常使用的资源类型: web

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

form表单中能够定义enctype属性,该属性的含义是在发送到服务器以前应该如何对表单数据进行编码。spring

默认的状况下,表单数据会编码为 "application/x-www-form-unlencoded".json

enctype经常使用的属性值以下:application/x-www-form-unlencoded: 在发送前编码全部字符(默认状况下);
multipart/form-data, 不对字符编码。在使用文件上传时候,使用该值。后端

 

请求体中嵌套数组的话,或复杂的格式的话,建议使用application/json传递比较好,后端解析会方便不少, 经过json的形式将数据发送给服务器。数组

json的形式的优势是它能够传递结构复杂的数据形式服务器

 

参数绑定

参数传递能够说是服务端和外界沟通的主要方式,这节是很是重要的!
 app

经过url传参
    |---get方式Url传参
        |---@PathVariable 即:url/id/1994 形式
        |---@RequestParam 即:url?username=zed形式
    |---POST方式传参
        |---@RequestParam
        |---请求体中加入文本
配置文件传参

get方式Url传参:

@PathVariabletcp

@RestController
public class HelloController {
    @GetMapping("/hello/{name}")
    public String hello(@PathVariable("name") String name){
        // 形参的name能够随意
        System.out.println("获取到的name是:"+name);
        return "hello "+name;
    }
}

get方式Url传参:

@RequestParam

若是请求参数的名字跟方法中的形参名字一致能够省略@RequestParam("name")

@GetMapping("/hello")
public String hello(@RequestParam("name") String name){
    System.out.println("获取到的name是:"+name);
    return "hello "+name;
}

3.get方式Url传参:

@RequestParam+默认参数

@GetMapping("/hello")
    public String hello(@RequestParam(value = "name",defaultValue = "admin") String name){
        System.out.println("获取到的name是:"+name);
        return "hello "+name;
    }

注意:若是没有指定默认值,而且没有传递参数将会报错

Required String parameter 'name' is not present :name参数没有提供

  • 解决方案
    • 1.defaultValue = "xxx" :使用默认值
    • 2.required = false :标注参数是非必须的
@GetMapping("/hello")
public String hello(@RequestParam(value = "name",required = false) String name){
    System.out.println("获取到的name是:"+name);
    return "hello "+name;
}

POST方式传递数据

@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传递字符串文本

@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接收参数

@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;
}

更多可参考原文:  https://www.jianshu.com/p/ad13fc37b047

案例

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 直传, 可获取到值 ;  @RequestParam 无关紧要
     * @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 有效, 存在默认值
     * @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 提交时:  可获取
     * x-www-urlencoded 提交时: 可获取
     * raw json体格式提交时:没法获取, 必须使用@RequestBody注解获取
     * @param user
     * @return
     */
    @PostMapping("test2")
    public Object test04(User user) {
        return user.getName() + "---------" + user.getPass();
    }

    /**
     * 必须是json体格式接收
     * @param user
     * @return
     */
    @PostMapping("test2-1")
    public Object test05(@RequestBody User user) {
        return user.getName() + "---------" + user.getPass();
    }

    /**
     * form-data 提交时:  可获取
     * x-www-urlencoded 提交时: 可获取
     * raw json体格式提交时:没法获取
     * @param name
     * @param pass
     * @return
     */
    @PostMapping("test2-3")
    public Object test042(@RequestParam String name,String pass) {
        return name+ "-----------------"+pass;
    }
}

 

重点: 划线

multipart/form-data与x-www-form-urlencoded区别

               multipart/form-data:既能够上传文件等二进制数据,也能够上传表单键值对,只是最后会转化为一条信息;

               x-www-form-urlencoded:只能上传键值对,而且键值对都是间隔分开的。好比,name=java&age=23;特殊字符须要转义成utf-8编号,如空格会变成 %20

raw

                能够上传任意格式的文本,能够上传text、json、xml、html等

请求体更多可参考文章: https://blog.csdn.net/pomer_huang/article/details/79495346 

相关文章
相关标签/搜索