前后台传递参数的编码方式

本文介绍了HTML form表单的enctype属性及其对Content-Type的影响。Content-Type默认为'application/x-www-form-urlencoded;charset=utf-8',并讨论了三种enctype值:'application/x-www-form-urlencoded'、'multipart/form-data'、'text/plain'。同时,文章阐述了前台以'application/x-www-form-urlencoded'和'application/json'编码方式发送数据,后台如何对应接收。

1、简要描述

enctype是指HTML页面中form表单的属性,它就是Content-Type的值。

Content-Type是HTTP请求头中的一个属性。

在jQuery中,ajax请求,Content-Type的默认值就是application/x-www-form-urlencoded;charset=utf-8

举例:

enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码。

默认地,表单数据会编码为 "application/x-www-form-urlencoded"。就是说,在发送到服务器之前,所有字符都会进行编码(空格转换为 "+" 加号,特殊符号转换为 ASCII HEX 值)。

enctype只有三个值:application/x-www-form-urlencoded、multipart/form-data、text/plain

<form action="form_action.asp" enctype="text/plain">
  <p>First name: <input type="text" name="fname" /></p>
  <p>Last name: <input type="text" name="lname" /></p>
  <input type="submit" value="Submit" />
</form>

2、主要编码方式

前台使用application/x-www-form-urlencoded,

后台接收方式如下:

@PostMapping(value = "/test")
public String test1(@RequestParam(name = "username") String username,
                    @RequestParam(name = "password") String password) {
    LOGGER.info("收到的参数:username: {}, password: {}", username, password);
    return "leihou";
}

前台使用application/json

//请求数据
var data = {name:'jack',sex:'man'};
//请求数据序列化处理
JSON.stingify(data);

后台接收方式如下:

@PostMapping(value = "/test")
public String test2(@RequestBody User user) {
    LOGGER.info("收到的参数:username: {}, password: {}", 
                user.getUsername(), 
                user.getPassword());
    return "leihou";
}

@Data
public class User {
    private String username;
    private String password;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值