总结:前后台接口参数接收的几种方式(form表单、ajax、restful、requestParam等)

知识前言:

1.Content-Type:  一个请求都会有请求的内容类型,默认是application/x-www-form-urlencoded; charset=UTF-8

常见的接种请求数据类型:

application/x-www-form-urlencoded

1)浏览器的原生form表单
2) 提交的数据按照 key1=val1&key2=val2 的方式进行编码,key和val都进行了URL转码

multipart/form-data

常见的 POST 数据提交的方式。我们使用表单上传文件时,必须让 form 的 enctype 等于这个值。

application/json

消息主体是序列化后的 JSON 字符串,这个类型越来越多地被大家所使用

text/xml

是一种使用 HTTP 作为传输协议,XML 作为编码方式的远程调用规范

情况一、传统form表单,submit提交

contentType:application/x-www-form-urlencoded

html

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form id="myform" action="/getFormData">
<!--注意input 必须要有name属性,后台才能接收到-->
   <input type="text" name="userName" placeholder="请输入名字"/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>

后台:

    @RequestMapping(value = "/getFormData")
    @ResponseBody //如果用了模板,比如themleaf那必须返回一个页面名,否则就要加这个参数
    public void getFormData(User user) {
        System.out.println(user);
    }

User

package com.model;

import lombok.Data;

import java.io.Serializable;
import java.util.Date;
@Data
public class User implements Serializable {
    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column t_user.user_id
     *
     * @mbg.generated Sat Jan 01 17:44:35 CST 2022
     */
    private Long userId;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column t_user.user_name
     *
     * @mbg.generated Sat Jan 01 17:44:35 CST 2022
     */
    private String userName;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column t_user.age
     *
     * @mbg.generated Sat Jan 01 17:44:35 CST 2022
     */
    private Integer age;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column t_user.password
     *
     * @mbg.generated Sat Jan 01 17:44:35 CST 2022
     */
    private String password;

    /**
     *
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database column t_user.create_time
     *
     * @mbg.generated Sat Jan 01 17:44:35 CST 2022
     */
    private String createTime;

    /**
     * This field was generated by MyBatis Generator.
     * This field corresponds to the database table t_user
     *
     * @mbg.generated Sat Jan 01 17:44:35 CST 2022
     */
    private static final long serialVersionUID = 1L;

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table t_user
     *
     * @mbg.generated Sat Jan 01 17:44:35 CST 2022
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(getClass().getSimpleName());
        sb.append(" [");
        sb.append("Hash = ").append(hashCode());
        sb.append(", userId=").append(userId);
        sb.append(", userName=").append(userName);
        sb.append(", age=").append(age);
        sb.append(", password=").append(password);
        sb.append(", createTime=").append(createTime);
        sb.append("]");
        return sb.toString();
    }
}

注意form提交的contentType

Content-Type: application/x-www-form-urlencoded

 如果我把后台的请求类型改成json

    @RequestMapping(value = "/getFormData",method = RequestMethod.POST,consumes ="application/json")
    @ResponseBody
    public void getFormData(User user) {
        System.out.println(user);
    }

报错提示:类型不支持 

 总结:

1.form表单中input要有name,否则后台获取不到。

2.form表单用input submit提交action,springmvc后台直接用对象接。

情况二、get提交,用requestParam接收

注意这种方式就是get提交,后台不能设置为post类型
http://127.0.0.1:8111/requestParam?userName=1&b=2

后台:

    @RequestMapping(value = "/requestParam",method = RequestMethod.GET)
    @ResponseBody
    public void requestParam( User user, int b,@RequestParam("b") int c) {
        System.out.println(user);
        System.out.println(b);
        System.out.println(c);
    }

返回结果:

User [Hash = 1244975268, userId=null, userName=1, age=null, password=null, createTime=null]
2
2

也就是说get提交,也可以直接参数获取,用RequestParam 可以指定变量名。

情况三、pathVariable 的get请求

http://127.0.0.1:8111/pathVariable/2

后台:

  @RequestMapping(value = "/pathVariable/{b}",method = RequestMethod.GET)
    @ResponseBody
    public void pathVariable(User user,@PathVariable("b") int c) {
        System.out.println(user);
        System.out.println(c);
    }

结果:
User [Hash = 1244954382, userId=null, userName=null, age=null, password=null, createTime=null]
2

post请求:

contentType:application/x-www-form-urlencoded

<button onclick="openR()">请求</button>

、、、、、   
 function openR(){
        // window.open("/requestParam?userName=1&b=2")
        $.ajax({
            url:'/pathVariable/2',
            method:'post'
        })
    }
    @RequestMapping(value = "/pathVariable/{b}",method = RequestMethod.POST)
    @ResponseBody
    public void pathVariable(User user,@PathVariable("b") int c) {
        System.out.println(user);
        System.out.println(c);
    }

情况四、jquery+ajax请求

(1)普通post请求

Content-Type:application/x-www-form-urlencoded;

function openR(){
    // window.open("/requestParam?userName=1&b=2")
    $.ajax({
        url:'/getMap',
        //请求方式
        type:'post',
        //请求的媒体类型
        // contentType: "application/json;charset=UTF-8",
        // dataType:"json",
        // data:JSON.stringify({a:1,b:2}),
        // data:"{\"userName\":22}",
        data:{userName:232},
        success:function (res) {
            alert("请求成功")
        }
    })
}

 后台:

    @RequestMapping(value = "/getMap",method = RequestMethod.POST)
    @ResponseBody
    public void getMap(User user)  {
        System.out.println(user);
    }

 如果form方式提交,后台用@ResponseBody修饰会怎么样??

会报错:

Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported]

(2)json请求

一般情况下都会用json来请求,特别是前后端分离的情况,这个时候,下面这样写是不能取到的,只有form类型提交才能取到下面的写法。JSON需要用@RequestBody

public void getMap(User user)
    function openR(){
        // window.open("/requestParam?userName=1&b=2")
        $.ajax({
            url:'/getMap',
            //请求方式
            type:'post',
            //请求的媒体类型
            contentType: "application/json;charset=UTF-8",
            // dataType:"json", //如果定义了这个,那么返回类型必须要json,否则不会进入success
            data:JSON.stringify({userName:1,b:2}),
            // data:"{\"userName\":22}",
            // data:{userName:235552},
            success:function (res) {
                alert("请求成功")
            }
        })
    }

注意:

data:JSON.stringify({userName:1,b:2}),
或者
data:"{\"userName\":22}",
总之要是json字符串

后台:要带上@RequestBody

    @RequestMapping(value = "/getMap",method = RequestMethod.POST)
    @ResponseBody
    public void getMap(@RequestBody User user)  {
        System.out.println(user);
    }
或者:用map接,也可以
    @RequestMapping(value = "/getMap",method = RequestMethod.POST)
    @ResponseBody
    public void getMap(@RequestBody Map user)  {
        System.out.println(user);
    }

 (3)后台单个字段接 form类型请求

前台:


    function openR(){
        // window.open("/requestParam?userName=1&b=2")
        $.ajax({
            url:'/getMap',
            //请求方式
            type:'post',
            //请求的媒体类型
            // contentType: "application/json;charset=UTF-8",
            // dataType:"json",
            // data:JSON.stringify({userName:1,b:2}),
            // data:"{\"userName\":22}",
            data:{userName:235552},
            success:function (res) {
                alert("请求成功"+JSON.stringify(res))
            }
        })
    }

后台:

   @RequestMapping(value = "/getMap",method = RequestMethod.POST)
    @ResponseBody
    public void getMap(String userName)  {
        System.out.println(userName);
    }

注意:参数名一定要和传过来的名字相同 

(4)单个字段  json串请求

 function openR(){
        // window.open("/requestParam?userName=1&b=2")
        $.ajax({
            url:'/getMap',
            //请求方式
            type:'post',
            //请求的媒体类型
            contentType: "application/json;charset=UTF-8",
            // dataType:"json",
            data:JSON.stringify({userName:1,b:2}),
            // data:"{\"userName\":22}",
            // data:{userName:235552},
            success:function (res) {
                // alert("请求成功"+JSON.stringify(res))
            }
        })
    }

 后台:

    @RequestMapping(value = "/getMap",method = RequestMethod.POST)
    @ResponseBody
    public void getMap(@RequestBody  String userName)  {
        System.out.println(userName);
    }

这个也是比较容易犯错的地方,这个时候,你以为取到userName的值是1?? NONONO,它取到的是一个json字符串  String userName= "{userName:1,b:2}";

正确的写法是用map接

    @RequestMapping(value = "/getMap",method = RequestMethod.POST)
    @ResponseBody
    public void getMap(@RequestBody  Map userName)  {
        System.out.println(userName);
    }

总结:

1.form表单action提交时,input中name必须有。

2.application/x-www-form-urlencoded格式请求(浏览器默认的方式),后台可以直接用对象接收或者单个字段类型接(String/Integer)。

3.application/x-www-form-urlencoded格式请求,后台不能用@RequestBody修饰,会报错:不支持这种方式请求。

4.application/json数据格式请求,后台要用@RequestBody修饰。

5.application/json数据格式请求,不能用单个字段接(String/Integer),只能用bean对象或者map接。


版权声明:本文为x18094原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。